Skip to content

Commit a664117

Browse files
Create 767-Reorganize-String.java
1 parent 5e77ff2 commit a664117

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+
class Solution {
4+
public String reorganizeString(String s) {
5+
HashMap<Character, Integer> map = new HashMap<>();
6+
for (int i = 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 = new PriorityQueue<>((a,b)->b.getValue()-a.getValue());
10+
pq.addAll(map.entrySet());
11+
12+
StringBuilder sb = new StringBuilder();
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+
return sb.toString();
39+
}
40+
}

0 commit comments

Comments
 (0)