题目
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 N = S.length();
int[] cnt = new int[256];//count ASCII(256)
char mc = 'a';//most frequent char(default 'a')
//Frequency statistics
for(char c:S.toCharArray())
{
cnt[c]++;
mc = (cnt[c]>cnt[mc])?c:mc;//most frequent char
}
//return ""
if((N-cnt[mc])<(cnt[mc]-1))
return "";
//return one possible case
StringBuilder[] sb = new StringBuilder[cnt[mc]];
for(int i=0;i<cnt[mc];i++)
{
sb[i] = new StringBuilder();
sb[i].append(mc);
}
int k = 0;
//Loop interpolation
for(char c ='a';c<='z';c++)// defult in a~z
{
while(cnt[c]>0&&c!=mc)
{
sb[k++].append(c);
cnt[c]--;
k%=cnt[mc];//loop
}
}
for(int i=1;i<cnt[mc];i++)
sb[0].append(sb[i]);
return sb[0].toString();
}
}