我写了一个递归方法,它可以从字符串中的字符中获取所有可能的字符组合。我也有一个方法来访问它,并返回一个组合列表:递归方法在java中通过控制台工作,但不适用于android
public static void uns(String word, StringBuilder s, List combos)
{
for(char c: word.toCharArray())
{
s.append(c);
if(word.length() != 1)
{
uns(removeChar(word, c),s,combos);
}
else
{
combos.add(s.toString());
}
s.deleteCharAt(s.toString().length()-1);
}
}
public static List getCombinations(String word)
{
List<String> combinations = new ArrayList<String>();
uns(word,new StringBuilder(),combinations);
return combinations;
}
public static String removeChar(String s, char c)
{
int index = s.indexOf(c);
return s.substring(0,index)+s.substring(index+1);
}
当用Java测试它时,它运行时没有任何缺陷。出于某种原因,当我在Android中使用它时,列表中填充了正确数量的元素,但每个元素都是相同的。例如,对于“here”这个词,它会返回一个填充“eerh”的列表。
'removeChar()'的定义是什么? – Eric 2013-02-18 02:16:40
@Eric对不起,编辑回。 – Wilson 2013-02-18 02:18:29