我试图在一个单词的垂直模式中从左上角到右下角搜索我的多维数组6x8网格,但我无法弄清楚我的代码有什么问题。有人能告诉我我做错了吗?
public static String findTopToBottom (char[][]board, String word) {
char[] letters = word.toCharArray();
for (int i = 0; i <= board[i].length; i++) {
for (int j = 0; j <= board.length; j++) {
boolean found = true;
for (int k = 0; k < letters.length; k++) {
if ((i + k > board[j].length) || (letters[k] != board[j][i+k])) {
found = false;
break;
}
}
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
}
答案 0 :(得分:2)
if ((i + k > board[j].length) || (letters[k] != board[j][i+k])) {
如果i + k
等于board[j].length
,将抛出越界异常,因为索引仅从0变为.length - 1
。使用>=
代替>
。
出于同样的原因,以下<=
需要更改为<
:
for (int i = 0; i <= board[i].length; i++) {
for (int j = 0; j <= board.length; j++) {
因为最大可能索引为.length - 1
。
而且:
for (int i = 0; i <= board[i].length; i++) {
即使将<=
更改为<
,看起来也是错误的。 i
索引应该是数组中列的索引,但是当您说board[i].length
时,您将i
视为行索引。这对于6x8阵列不会造成问题,但是对于8x6阵列也是如此,因为您希望i
从0到7,但是当i=6
时,board[6].length
将会超出范围。如果您确定所有行的长度都相同,则应将其更改为
for (int i = 0; i < board[0].length; i++) {
答案 1 :(得分:1)
检查我的解决方案:
public static String findTopToBottom(char[][] board, String word) {
char[] letters = word.toCharArray();
if (letters.length <= board.length) {
int lettersIndex = 0;
for (int r = 0; r < board.length; r++) {
// scan horizontally
for (int c = 0; c < board[r].length; c++) {
if (board[r][c] == letters[0]) {
// found first letter now scan vertically
lettersIndex++;
// now go down
for (int r1 = r+1; r1 < board.length; r1++) {
if (c < board[r1].length && board[r1][c] == letters[lettersIndex]) {
lettersIndex++;
if (lettersIndex == letters.length) {
return "String " + word + " found in row=" + r + " col=" + c;
}
} else {
// no break it
lettersIndex = 0;
break;
}
}
}// found first
}
}
}
return "String " + word + " not found";
}
它可以在任何类型的数组中工作。
所以我算法的步骤是: