public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
String str= scn.nextLine();
str=str.substring(5,str.length()-1);
System.out.println(reorganizeString(str));
}
public static String reorganizeString(String str) {
//maintain count or occurrence of characters in str.
Map<Character,Integer> map=new HashMap<>();
for(char cc: str.toCharArray()) {
map.put(cc,map.getOrDefault(cc,0)+1);
}
PriorityQueue<Character> maxHeap=new PriorityQueue<>((x,y) -> map.get(y)-map.get(x));
maxHeap.addAll(map.keySet());
StringBuilder sb =new StringBuilder();
while(maxHeap.size()>1) {
char cc1=maxHeap.remove();
char cc2=maxHeap.remove();
sb.append(cc1);
sb.append(cc2);
map.put(cc1,map.get(cc1)-1);
map.put(cc2,map.get(cc2)-1);
if(map.get(cc1)>0) {
maxHeap.add(cc1);
}
if(map.get(cc2)>0) {
maxHeap.add(cc2);
}
}
if(maxHeap.size()==1) {
char cc=maxHeap.remove();
int occ=map.get(cc);
if(occ>1) {
return "";
}else {
sb.append(cc);
}
}
return sb.toString();
}
Test case 2 and 3 are showing wrong answers
@Utkarsh-Patiyal-2067329909961088
Actually your code is correct but in two output files there is one space in the end like "aaaabc ".
So when you tries to convert str into array, It takes last space as character and results in wrong output.
Example for this testcase “aaaabc " you code is giving “abaca a” as output but output should be “” (empty string”.
So add if(cc==’ '){ continue; } condition just after line 17 will lead to correct output.
for the input S = “aaaabbc” ,output is turning out to be this ababa"ca, I can’t figure out what’s the problem
@Utkarsh-Patiyal-2067329909961088
Please don’t end input as S = “aaaabbc” , just input aaaabbc
Here is the updated code https://ide.codingblocks.com/s/288443
thanks a lot ,it worked