|
| 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 | +} |