zoukankan      html  css  js  c++  java
  • LeetCode

    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].

    贪心

    class Solution {
        public String reorganizeString(String S) {
            if (S == null || S.length() <= 0)
                return "";
            int[] chs = new int[26];
            for (int i=0; i<26; i++) {
                chs[i] = 0;
            }
            for (int i=0; i<S.length(); i++) {
                chs[S.charAt(i)-'a']++;
            }
            StringBuilder ret = new StringBuilder();
            char curChar = findMaxChar(chs, -1);
            while (curChar != '#' && curChar != '$') {
                ret.append(curChar);
                curChar = findMaxChar(chs, ret.charAt(ret.length()-1)-'a');
            }
            if (curChar == '$')
                return ret.toString();
            else
                return "";
        }
        
        private char findMaxChar(int[] chs, int target) {
            char ret = '#';
            int maxCnt = 0, cnt=0;
            for (int i=0; i<26; i++) {
                if (chs[i] == 0)
                    cnt ++;
                if (maxCnt < chs[i] && i!=target) {
                    maxCnt = chs[i];
                    ret = (char)(i+'a');
                }
            }
            if (cnt == 26)
                return '$';
            if (ret != '#')
                chs[ret-'a']--;
            return ret;
        }
    }
  • 相关阅读:
    comm---两个文件之间的比较
    fgrep---指定的输入文件中的匹配模式的行
    zip---解压缩文件
    unzip---解压缩“.zip”压缩包。
    tar---打包,解压缩linux的文件和目录
    scp---远程拷贝文件
    make---GNU编译工具
    gcc---C/C++ 编译器
    expr---计算工具
    curl -w 支持的参数
  • 原文地址:https://www.cnblogs.com/wxisme/p/9504180.html
Copyright © 2011-2022 走看看