• 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();
        }
    }
  • 相关阅读:
    nginx 代理概念理解
    nginx反向代理(proxy_pass)tomcat的过程中,session失效的问题解决
    Mybatis-Generator 详解 http://www.cnblogs.com/jtzfeng/p/5254798.html
    web容器线程数和程序中线程阻塞导致 请求超时
    教程-Delphi操作快捷键
    PC-博客首页中增加必应或GOOGLE搜索功能
    PC-大概最全的黑客工具表了
    PC-计算机动行命令里的密密!系统管理程序!
    PC-红警联机问题与下载
    PC-破解RAR软件注册问题
  • 原文地址:https://www.cnblogs.com/fatttcat/p/9989496.html
Copyright © 2020-2023  润新知