# 1405. Longest Happy String ###### tags: `Leetcode` `Medium` `Greedy` `Microsoft` Link: https://leetcode.com/problems/longest-happy-string/ ## 思路 每轮放置字符时优先先放剩余次数最多的, 如果上次放的2个字符和剩余个数最多的字符相同,则放置次多的字符 ## Code ```java= class Solution { public String longestDiverseString(int a, int b, int c) { StringBuffer sb = new StringBuffer(); int[] freq = new int[3]; freq[0] = a; freq[1] = b; freq[2] = c; Queue<Integer> pq = new PriorityQueue<>((e1,e2)->freq[e2]-freq[e1]); if(a!=0) pq.add(0); if(b!=0) pq.add(1); if(c!=0) pq.add(2); while(!pq.isEmpty()){ int num = pq.poll(); if(sb.length()>=2 && num==(int)sb.charAt(sb.length()-1)-97 && num==(int)sb.charAt(sb.length()-2)-97){ if(pq.isEmpty()) break; int num2 = pq.poll(); pq.add(num); num = num2; } sb.append((char)(num+97)); if(--freq[num]!=0) pq.add(num); } return sb.toString(); } } ```