Loading

leetcode767. 重构字符串

题目:https://leetcode-cn.com/problems/reorganize-string/submissions/

题解:要使相邻的字符不重复,那么存在一种情况:当一个字符出现次数大于总字符数一半时,那么一定存在相同字符相邻。为了不使相同字符相邻,那么每个字符都应该与自己上一个字符相隔一个位置,如“a#a”这样,‘#’表示空位置,当要设置的位置超过了字符串的长度,那么应该从1位置重新开始设置,例如:输入“aabb”,那么先排列‘a’,有“a#a#”,再排列‘b’,因为此时‘b’的位置超过了输入字符串长度,所以从1位置开始排列,有“abab”。但要优先考虑相同数量最多的字符,因为,假设“aabbbc”为输入,那么先排列‘a',有“a#a###”,再排列‘b’,有“ababb#”,可以看到数量最多的‘b’在依次排列时,可能会与自己相邻,所以先排列‘b’(数量最多的字符)就能避免这种情况。

代码:

class Solution {
    public String reorganizeString(String S) {
        int[] map = new int[26];
        for(char c : S.toCharArray()){
            map[c - 'a'] ++;
        }
        List<NewChar> list = new ArrayList<>();
        for(int i=0; i<26; i++){
            if (map[i] > 0) {
                if(map[i] > (S.length() + 1) / 2)  //超出一半,一定会相邻
                    return "";
                list.add(new NewChar((char) ('a' + i), map[i]));
            }
        }
        Collections.sort(list, (a, b) -> b.count - a.count);
        char[] res = new char[S.length()];
        int i = 0, index = 0;
        while (i < list.size()) {
            while (list.get(i).count-- > 0) {
                if (index >= res.length) {  //超出了字符串长度,从1开始
                    index = 1;
                }
                res[index] = list.get(i).c;
                index += 2;  //每次相隔一位
            }
            i++;
        }
        return String.valueOf(res);
    }
    class NewChar{
        char c;
        int count;
        public NewChar(char c, int cnt){
            this.c = c;
            this.count = cnt;
        }
    }
}

 

posted @ 2020-11-30 18:02  yoyuLiu  阅读(106)  评论(0编辑  收藏  举报