zoukankan      html  css  js  c++  java
  • 767. Reorganize String

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

    If possible, output any possible result.  If not possible, return the empty string.

    Example 1:

    Input: S = "aab"
    Output: "aba"
    

    Example 2:

    Input: S = "aaab"
    Output: ""
    

    Note:

    • S will consist of lowercase letters and have length in range [1, 500].

    扫一遍S统计频率。如果某个字母的个数比S.length()+1的一半还多,无法reorganize,返回空。维护一个max heap,按字母出现的次数排序。

    用greedy,每次都用出现次数最多的字母当作下一个字符,并比较是否与sb的最后一个字符相等,若sb为空或者不等,append字符之后,判断一下该字符的次数减一是否大于0,若小于0就不用再offer回max heap了。如果第一次poll出来的字符和sb的最后一个字符相等,再poll一个pair出来,用同样方法处理,记得要把第一次poll出来的pair再offer回去!

    时间:O(NlogN),空间:O(N)

    class Solution {
        public String reorganizeString(String S) {
            HashMap<Character, Integer> map = new HashMap<>();
            for(char c : S.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
                if(map.get(c) > (S.length() + 1) / 2)
                    return "";
            }
            
            PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> (b[1] - a[1]));
            for(Map.Entry<Character, Integer> entry : map.entrySet()) {
                maxHeap.offer(new int[] {entry.getKey(), entry.getValue()});
            }
            
            StringBuilder sb = new StringBuilder();
            while(!maxHeap.isEmpty()) {
                int[] pair = maxHeap.poll();
                if(sb.length() == 0 || sb.charAt(sb.length() - 1) != (char)pair[0]) {
                    sb.append((char)pair[0]);
                    if(--pair[1] > 0)
                        maxHeap.offer(new int[] {pair[0], pair[1]});
                }
                else {
                    int[] pair2 = maxHeap.poll();
                    sb.append((char)pair2[0]);
                    if(--pair2[1] > 0)
                        maxHeap.offer(new int[] {pair2[0], pair2[1]});
                    maxHeap.offer(new int[] {pair[0], pair[1]});
                }
            }
            return sb.toString();
        }
    }
  • 相关阅读:
    flume杀掉重启
    Tomcat访问日志浅析 (转)
    httpclient Accept-Encoding 乱码
    解决Maven报Plugin execution not covered by lifecycle configuration
    mahout基于Hadoop的CF代码分析(转)
    hadoop Mahout中相似度计算方法介绍(转)
    nginx配置文件结构,语法,配置命令解释
    nginx 中文和英文资料
    使用异步 I/O 大大提高应用程序的性能
    nginx AIO机制与sendfile机制
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9989496.html
Copyright © 2011-2022 走看看