1
给定一串字,说“OhMy”,保持大写字母固定(不变),但我们可以改变小写字母的位置。输出所有可能的排列。查找某个字符串的所有排列不变
例如。给予 “OhMy” 应该输出[ “OhMy”, “OyMh”]
这里是我做过什么:
public static List<String> Permutation(String s){
List<String> res = new ArrayList<String>();
if (s == null || s.length() == 0){
return res;
}
StringBuilder path = new StringBuilder(s);
List<Character> candidates = new ArrayList<Character>();
List<Integer> position = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (Character.isAlphabetic(c) && Character.isLowerCase(c)){
candidates.add(c);
position.add(i);
}
}
boolean[] occurred = new boolean[candidates.size()];
helper(res, path, candidates, position, 0);
return res;
}
public static void helper(List<String> res, StringBuilder path, List<Character> candidates, List<Integer> position, int index){
if (index == position.size()){
res.add(path.toString());
return ;
}
for (int i = index; i < position.size(); i++){
for (int j = 0; j < candidates.size(); j++){
path.setCharAt(position.get(i), candidates.get(j));
char c = candidates.remove(j);
helper(res, path, candidates, position, index+1);
candidates.add(j, c);
}
}
}
输入 “ABC” 就会有结果[ABC,ACB,加, Acb] 本质上,外部循环遍历每个可能的位置,内部循环尝试每个可能的位置上的每个可能的候选。 我不知道它为什么重复li“Acc,Acb”
你的问题是什么? – Kevin 2014-10-10 18:43:18