classSolution{ /** 贪心:在同一字符相邻小于3的情况下,取剩余最多的字符进行拼接,否则不用第3个字符,取剩余数第二多的字符拼接 */ public String longestDiverseString(int a, int b, int c){ //1. 定义大根堆,目的是进行字符剩余数量的排序 PriorityQueue<int[]> mostCountQueue = new PriorityQueue<>((x,y)->y[1]-x[1]); mostCountQueue.add(newint[]{'a', a}); mostCountQueue.add(newint[]{'b', b}); mostCountQueue.add(newint[]{'c', c});
//2. 定义结果字符串 StringBuilder sb = new StringBuilder();
//3. 遍历堆的取出操作,直至堆空 while (!mostCountQueue.isEmpty()) { int[] cur = mostCountQueue.poll();
// 4. 判断取出字段是否可能组成同一字符相邻出现3个的情况,如果是,则不用第3个字符,取剩余数第二多的字符拼接 int n =sb.length(); if (n >= 2 && sb.charAt(n - 1)== cur[0] && sb.charAt(n - 2)== cur[0]) { if (mostCountQueue.isEmpty()) break; //注意堆空的情况:不存在剩余数第二多的字符 int[] temp = cur; // temp暂存旧cur cur = mostCountQueue.poll(); // 取剩余数第二多的字符作为新cur mostCountQueue.add(temp); // temp重新放入堆 }
// 5. 如果数量大于0,拼接字符 if (cur[1] > 0){ sb.append((char)cur[0]);