Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit94884ec

Browse files
Create 767-Reorganize-String.java
1 parentfc5a9a7 commit94884ec

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎java/767-Reorganize-String.java‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//See this comment for explanation https://leetcode.com/problems/reorganize-string/discuss/113440/Java-solution-PriorityQueue/211009
2+
3+
classSolution {
4+
publicStringreorganizeString(Strings) {
5+
HashMap<Character,Integer>map =newHashMap<>();
6+
for (inti =0;i<s.length();i++) {
7+
map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
8+
}
9+
PriorityQueue<Map.Entry<Character,Integer>>pq =newPriorityQueue<>((a,b)->b.getValue()-a.getValue());
10+
pq.addAll(map.entrySet());
11+
12+
StringBuildersb =newStringBuilder();
13+
14+
while (!pq.isEmpty()) {
15+
Map.Entry<Character,Integer>temp1 =pq.poll();
16+
//if the character at sb's end is different from the max frequency character or the string is empty
17+
if (sb.length()==0 ||sb.charAt(sb.length()-1)!=temp1.getKey()) {
18+
sb.append(temp1.getKey());
19+
//update the value
20+
temp1.setValue(temp1.getValue()-1);
21+
}else {//the character is same
22+
//hold the current character and look for the 2nd most frequent character
23+
Map.Entry<Character,Integer>temp2 =pq.poll();
24+
//if there is no temp2 i.e. the temp1 was the only character in the heap then there is no way to avoid adjacent duplicate values
25+
if (temp2==null)
26+
return"";
27+
//else do the same thing as above
28+
sb.append(temp2.getKey());
29+
//update the value
30+
temp2.setValue(temp2.getValue()-1);
31+
//if still has some value left add again to the heap
32+
if (temp2.getValue()!=0)
33+
pq.offer(temp2);
34+
}
35+
if (temp1.getValue()!=0)
36+
pq.offer(temp1);
37+
}
38+
returnsb.toString();
39+
}
40+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp