forked from ashoklathwal/Code-for-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResarrangeString.java
67 lines (58 loc) · 1.2 KB
/
ResarrangeString.java
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
import java.util.*;
class ResarrangeString
{
class pair implements Comparable<pair>
{
char ch;
int count;
@Override
public int compareTo(pair obj)
{
return obj.count - this.count;
}
}
public void resarrangeString_util(String str)
{
PriorityQueue<pair> maxheap = new PriorityQueue<>();
int[] arr = new int[26];
for(char ch : str.toCharArray())
arr[ch-'a']++;
for(int i=0;i<26;i++)
{
if(arr[i] != 0)
{
pair pr = new pair();
pr.ch = (char)(i+'a');
pr.count = arr[i];
maxheap.add(pr);
}
}
pair prev = null;
StringBuffer sb= new StringBuffer();
while(!maxheap.isEmpty())
{
pair curr = maxheap.poll();
if(curr.count == 0)
break;
curr.count--;
sb.append(curr.ch);
if(prev != null)
maxheap.add(prev);
prev = curr;
}
if(sb.length() == str.length())
{
System.out.println("valid String : "+sb.toString());
}
else
{
System.out.println("Invalid String");
}
}
public static void main(String[] args)
{
String str = "aaabc";
ResarrangeString re = new ResarrangeString();
re.resarrangeString_util(str);
}
}