如果字符串数组中的字符串与给定值匹配,则此处的所有答案都匹配,但我认为这不是您要查找的内容:/ 我已经创建了一个自定义方法,该方法与特定单词匹配是字符的一部分[][] 数组。
public static Boolean wordExistsInCharArray(char[][] puzzle, String word) {
char[] charArray = word.toCharArray();
//search array for words only! A word is defined when there is a whitespace on both sides or start/end of input.
int currentWordIndex, charArrayIndex;
for (int i = 0; i < puzzle.length; i++) {
currentWordIndex = 0;
charArrayIndex = 0;
for (int j = 0; j < puzzle[i].length; j++) {
if (puzzle[i][j] == ' ') { //word has ended and we need to check if it matches the one we are looking for.
currentWordIndex = 0;
if (charArrayIndex == charArray.length) {
return true; // all the characters in the word were presented in current puzzle row. You now have both i, j indexes.
}
charArrayIndex = 0;
} else {
currentWordIndex++; // extend current word length with one character
if (currentWordIndex - 1 == charArrayIndex) { // check if current word length and parsed characters length are equal otherwise just continue
if (charArrayIndex < charArray.length && charArray[charArrayIndex] == puzzle[i][j]) { // test if next character from charArray matches current word character
charArrayIndex++; // extend charArrayIndex if there is a match
} else {
charArrayIndex = 0; // reset charArrayIndex since there is no match or current word length is bigger than needed.
}
} else {
continue;
}
}
}
if (charArrayIndex == charArray.length) { // in the case when the puzzle[i] has ended and we did not check if we have any occurrence
return true; // all the characters in the word were presented in current puzzle row. You now have both i, j indexes.
}
}
return false;
}
然后进行如下测试:
char[][] puzzle1 = new char[][] {
{'f', 'o', 'o', ' ', 'b', 'a', 'r'},
{'f', 'o', 'o', ' ', 'b', 'u', 'z'},
{'f', 'o', 'o', ' ', 'f', 'i', 'g', 'h', 't', 'e', 'r'}
};
char[][] puzzle2 = new char[][]{
{'f', 'o', 'o', ' ', 'b', 'a', 'r'},
{'f', 'o', 'o', ' ', 'b', 'u', 'z'},
{'f', 'o', 'o', ' ', 'f', 'i', 'g', 'h', 't', 'e', 'r', 'e', 'u', 'r', 'o'}
};
char[][] puzzle3 = new char[][] {
{'f', 'o', 'o', ' ', 'b', 'a', 'r'},
{'f', 'o', 'o', ' ', 'b', 'u', 'z'},
{'f', 'o', 'o', ' ', 'e', 'u', 'r', 'o', 'f', 'i', 'g', 'h', 't', 'e', 'r'}
};
char[][] puzzle4 = new char[][] {
{'m', 'o', 't', 'h', ' ', 'i', 's', ' ', 'n', 'o', 't', ' ', 'a', ' ', 'r', 'e', 'a', 'l', ' ', 'w', 'o', 'r', 'd'}
};
char[][] puzzle5 = new char[][] {
{'I', ' ', 'l', 'o', 'v', 'e', ' ', 'm', 'y', ' ', 'm', 'o', 't', 'h', 'e', 'r', ' ', 'f', 'o', 'r', ' ', 'r', 'e', 'a', 'l'}
};
System.out.println(wordExistsInCharArray(puzzle1, "fighter"));
System.out.println(wordExistsInCharArray(puzzle2, "fighter"));
System.out.println(wordExistsInCharArray(puzzle3, "fighter"));
System.out.println(wordExistsInCharArray(puzzle4, "moth"));
System.out.println(wordExistsInCharArray(puzzle5, "moth"));
输出将是:
true
false
false
true
false