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”

+2

你的问题是什么? – Kevin 2014-10-10 18:43:18

回答

1

看来你隐含的问题的主要观点是如何有效地枚举给定集的所有排列,你可以在线阅读有几种方法)。如果您可以枚举小写字母的所有索引列表,那么做记录并将每个小写字母的排列与原始不变的大写字母集合合并在一起,尊重大写字母的位置非常简单你可以输出你的字符串。如果你对这部分有困难,更新你的问题,并且有人应该能够帮助你。

相关问题