我想制作一个程序,可以使某些单词不混杂。
我需要尝试所有可能组合的单词,然后检查它是否包含在名为dict
的String变量中。爪哇:'for'循环的未知数
我的代码是:
public class UnJumble
{
public static void main(String args[])
{
String dict = "cat, rat, mat dog, let, den, pen, tag, art,";
String t = "tra";
int l = t.length();
for(int i=0; i<l; i++)
{
char a=t.charAt(i);
t = t.replaceFirst(a+"","");
l--;
for(int j=0; j<l; j++)
{
char b = t.charAt(j);
t = t.replaceFirst(b+"","");
l--;
for(int k=0; k<l; k++)
{
char c = t.charAt(k);
if(dict.contains(""+a+b+c+","))
{
System.out.println("\'"+a+b+c+"\' found.");
break;
}
}
l++;
t = new StringBuilder(t).insert(j,b+"").toString();
}
t = new StringBuilder(t).insert(i,a+"").toString();
l++;
}
}
}
变量t
包含单词是未混乱。
有了这个代码,输出为:
'rat' found.
'art' found.
我想,我需要尽可能多的for
循环,因为作为字符字符串t
。
但我想使它能够解开未知长度的混乱单词。那么我怎么能做到这一点?
我试过在互联网上搜索,所以在SO上。我发现了一些用其他编程语言编写的答案,我不明白。
查找递归方法;) –
第一个循环,其中包含最多的两个词:可以制作的最大词的组合,即n个字母可以产生一定数量的组合(用于计算的搜索组合),或者总字典字数(以较低者为准)。 –
你只是想排列't'。见例如http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string – dejvuth