-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorganize_String.java
More file actions
82 lines (70 loc) · 2.01 KB
/
Copy pathReorganize_String.java
File metadata and controls
82 lines (70 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.
Return any possible rearrangement of s or return "" if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
*/
import java.util.*;
class Solution {
class Pair{
int freq ;
char character ;
Pair(int f , char c ) {
freq = f;
character = c ;
}
}
public String reorganizeString(String s) {
HashMap <Character , Integer> map = new HashMap <>();
for(char c : s.toCharArray()){
map.put(c, map.getOrDefault(c,0)+1);
}
PriorityQueue <Pair> heap = new PriorityQueue <>(
(a,b) ->{
if(a.freq != b.freq){
return b.freq - a.freq;
}
else{
return b.character - a.character;
}
}
);
for(Map.Entry<Character , Integer> entry : map.entrySet()){
int freq = entry.getValue();
char character = entry.getKey();
heap.add(new Pair(freq , character));
}
StringBuilder res = new StringBuilder();
while(!heap.isEmpty()){
if(res.length()==0 || res.charAt(res.length()-1)!= heap.peek().character){
Pair p = heap.poll();
res.append(p.character);
p.freq -- ;
if(p.freq != 0){
heap.add(p);
}
}
else {
Pair k = heap.poll();
if(heap.isEmpty()){
return "";
}
Pair p = heap.poll();
res.append(p.character);
p.freq--;
if(p.freq != 0){
heap.add(p);
}
heap.add (k);
}
}
return res.toString();
}
}