我正在制作一种方法,它将返回一个String[]
包含一个字母不同的单词的有效组合。该方法将String
包含单词字典的数组作为第一个参数,将另外两个分别包含单词 one 和 two 的字符串作为第二个和第三个参数。
这是我的方法:
public static String[] findCombos(String[] dict, String a, String b){
char[] wordA = a.toCharArray();
char[] wordB = b.toCharArray();
int length = wordA.length;
List<String> validCombos = new ArrayList<String>();
Arrays.sort(dict);
//wordA
for(int i = 0; i<length; i++){
char tmp = wordA[i];
wordA[i] = 0;
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString().trim();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
int lengthb = wordB.length;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString();
for(int j = 0; j<lengthb; j++){
tmpWordB = new StringBuffer(tmpWordB).insert(j ,tmp).toString();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordA[i] = tmp;
}
}
}else{
wordA[i] = tmp;
}
}
//wordB
int lengthb = b.length();
for(int i = 0; i<lengthb; i++){
char tmp = wordB[i];
wordB[i] = 0;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString().trim();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
int lengtha = a.length();
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString();
for(int j = 0; j< lengtha; j++){
tmpWordA = new StringBuffer(tmpWordA).insert(j, tmp).toString();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordB[i] = tmp;
}
}
}else{
wordB[i] = tmp;
}
}
String[] res = validCombos.toArray(new String[0]);
return res;
}
数组已经排序,我确定有问题的元素在数组中,但是搜索不断返回负数并自动分支到else
子句。有任何想法吗?这是字典的链接: