767. Reorganize String

Question

767. Reorganize String

Solution

题目大意:

给一个字符串,将字符按如下规则排序,相邻两个字符一同,如果相同返回空串否则返回排序后的串。

思路:

首先找出字符数量最大的字符,如果数量大于S长度的一半,返回空字符串,否则将该字符从索引0开始间隔着放(0,2,4,...),放到头再从索引1开始以2为步长放

Java实现:

public String reorganizeString(String S) {
    int[] letters = new int[26];
    for (char c : S.toCharArray()) {
        letters[c - 'a']++;
    }

    int maxIdx = 0;
    int max = letters[0];
    for (int i = 1; i < letters.length; i++) {
        if (max < letters[i]) {
            max = letters[i];
            maxIdx = i;
        }
    }

    if (max > Math.ceil(S.length() / 2.0)) {
        return "";
    }

    int tmpIdx = 0;
    char[] retArr = new char[S.length()];
    for (int j = 0; j < max; j++) {
        retArr[tmpIdx] = (char) (maxIdx + 'a');
        tmpIdx += 2;
    }
    for (int i = 0; i < letters.length; i++) {
        if (letters[i] > 0 && i != maxIdx) {
            for (int j = 0; j < letters[i]; j++) {
                if (tmpIdx >= S.length()) tmpIdx = 1;
                retArr[tmpIdx] = (char) (i + 'a');
                tmpIdx += 2;
            }
        }
    }
    return String.valueOf(retArr);
}
原文地址:https://www.cnblogs.com/okokabcd/p/9600749.html