美文网首页程序员
力扣 767 重构字符串

力扣 767 重构字符串

作者: zhaojinhui | 来源:发表于2020-11-16 01:13 被阅读0次

题意:给定一个字符串,重构字符串,让相同的字符,不相邻

思路:利用奇偶性,具体见代码注释

思想:字符规律

复杂度:时间O(n),空间O(n)

class Solution {
    public String reorganizeString(String S) {
        if(S == null)
            return S;
        int len = S.length();
        if(len == 0)
            return S;
        
        char[] arr = new char[len];
        int[] count = new int[256];
        int max = 0;
        int index = -1;
        // 遍历字符串,找出字符串中每一个字符的个数,以及出现最多的字符
        for(int i=0;i<len;i++) {
            int temp = (int)S.charAt(i);
            count[temp]++;
            if(count[temp] > max) {
                max = count[temp];
                index = temp;
            }
        }
        
        // 如果最多的字符超过了一般,返回空
        if(max > (len +1)/2)
            return "";
        
        int cnt = 0;
        
        // 把最多的字符隔一位放入结果
        while(count[index] > 0) {
            arr[cnt] = (char)index;
            cnt = cnt+2;
            count[index]--;
        }
        
        // 遍历count把每一个不为0的字符,隔一位加入结果
        for(int i=0;i<256;i++) {
            while(count[i] > 0) {
                // 当奇数位用完之后,从头开始用偶数位放元素
                if(cnt >= len) 
                    cnt = 1;
                arr[cnt] = (char)i;
                cnt = cnt+2;
                count[i]--;
            }
        }
        
        return new String(arr);
    }
}

相关文章

  • 力扣 767 重构字符串

    题意:给定一个字符串,重构字符串,让相同的字符,不相邻 思路:利用奇偶性,具体见代码注释 思想:字符规律 复杂度:...

  • LeetCode 767. 重构字符串

    1、题目 重构字符串 - 力扣(LeetCode) https://leetcode-cn.com/problem...

  • LeetCode 767 重构字符串

    题目 重构字符串 描述 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。若可行,输出任意可行...

  • 767. 重构字符串

    题目描述: 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。 若可行,输出任意可行的结果。若...

  • Leetcode767(Leetcode1054).重构字符串(

    Leetcode767. 重构字符串 题目描述 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不...

  • 767. 重构字符串(Python)

    难度:★★★☆☆类型:字符串方法:贪心算法 力扣链接请移步本题传送门[https://leetcode-cn.co...

  • 394. 字符串解码(Python)

    题目 难度:★★★☆☆类型:字符串方法:栈 力扣链接请移步本题传送门更多力扣中等题的解决方案请移步力扣中等题目录 ...

  • LeetCode | 面试题 01.06. 字符串压缩【Pyth

    LeetCode 面试题 01.06. 字符串压缩【Easy】【Python】【双指针】 问题 力扣 字符串压缩。...

  • 1021. 删除最外层的括号(Python)

    更多精彩内容,请关注【力扣简单题】。 题目 难度:★★☆☆☆类型:字符串 有效括号字符串为空 ("")、"(" +...

  • 『字符串』上升下降字符串1370

    题目相关 原题链接:1370. 上升下降字符串 - 力扣(LeetCode) 涉及知识:字符串、排序 题目难度:★...

网友评论

    本文标题:力扣 767 重构字符串

    本文链接:https://www.haomeiwen.com/subject/fpnmbktx.html