classSolution{public:stringreorganizeString(strings){unordered_map<char,int>count;intmaxFreq=0;for(constcharc:s)maxFreq=max(maxFreq,++count[c]);if(maxFreq>(s.length()+1)/2)return"";stringans;priority_queue<pair<int,char>>maxHeap;// (freq, c)intprevFreq=0;charprevChar='@';for(constauto&[c,freq]:count)maxHeap.emplace(freq,c);while(!maxHeap.empty()){// Get the most freq letterconstauto[freq,c]=maxHeap.top();maxHeap.pop();ans+=c;// Add the previous letter back so that// Any two adjacent characters are not the sameif(prevFreq>0)maxHeap.emplace(prevFreq,prevChar);prevFreq=freq-1;prevChar=c;}returnans;}};
publicclassSolution{publicStringreorganizeString(Strings){Map<Character,Integer>count=newHashMap<>();intmaxFreq=0;for(finalcharc:s.toCharArray()){count.merge(c,1,Integer::sum);maxFreq=Math.max(maxFreq,count.get(c));}if(maxFreq>(s.length()+1)/2)return"";StringBuildersb=newStringBuilder();// (freq, c)Queue<Pair<Integer,Character>>maxHeap=newPriorityQueue<>((a,b)->b.getKey()-a.getKey());intprevFreq=0;charprevChar='@';for(finalcharc:count.keySet())maxHeap.offer(newPair<>(count.get(c),c));while(!maxHeap.isEmpty()){// Get the most freq letterfinalintfreq=maxHeap.peek().getKey();finalcharc=maxHeap.poll().getValue();sb.append(c);// Add the previous letter back so that// Any two adjacent characters are not the sameif(prevFreq>0)maxHeap.offer(newPair<>(prevFreq,prevChar));prevFreq=freq-1;prevChar=c;}returnsb.toString();}}
classSolution:defreorganizeString(self,s:str)->str:count=Counter(s)ifmax(count.values())>(len(s)+1)//2:return''ans=[]maxHeap=[(-freq,c)forc,freqincount.items()]heapq.heapify(maxHeap)prevFreq=0prevChar='@'whilemaxHeap:# Get the most freq letterfreq,c=heapq.heappop(maxHeap)ans.append(c)# Add the previous letter back so that# Any two adjacent characters are not the sameifprevFreq<0:heapq.heappush(maxHeap,(prevFreq,prevChar))prevFreq=freq+1prevChar=creturn''.join(ans)