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) {
int[] record = new int[26];
int len = S.length();
int spe = -1;
for(char ch : S.toCharArray()){
record[ch - 'a']++;
}
for(int i = 0; i < 26; i++){
if(record[i] > (len + 1) / 2)
return "";
if(record[i] == (len + 1) / 2)
spe = i;
}
char[] chs = new char[len];
int it = 0;
if(spe != -1){
while(record[spe]-- > 0)
chs[it++] = (char)(spe + 'a');
}
for(int i = 0; i < 26; i++){
while(record[i]-- > 0)
chs[it++] = (char)(i + 'a');
}
//System.out.println(new String(chs));
char[] res = new char[len];
it = 0;
int left = 0, right = (len + 1) / 2;
while(right < len){
res[it++] = chs[left++];
res[it++] = chs[right++];
}
if(left < (len + 1) / 2)
res[it] = chs[left];
String str = new String(res);
return str;
}
}