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]
.
方法一:暴力实现,但肯定会TLE,因为字符串长度最长可以为500,500!是一个天文数字,因此肯定会TLE,但也是一种方法,程序如下所示:
class Solution {
String s = "";
public String reorganizeString(String S) {
char[] ch = S.toCharArray();
backTracingString(ch, new char[ch.length], 0, new HashSet<Integer>());
return s;
}
public boolean backTracingString(char[] ch, char[] res, int index, Set<Integer> set){
if (index == ch.length){
s = new String(res);
return true;
}
for (int i = 0; i < ch.length; ++ i){
if (set.contains(i)){
continue;
}
if (index > 0 && ch[i] == res[index-1]){
continue;
}
res[index] = ch[i];
set.add(i);
if (backTracingString(ch, res, index + 1, set)){
return true;
}
set.remove(i);
}
return false;
}
}
方法二:待补充