"给定2D字符数组和字符串。
查找特定字符串是否在矩阵中对角显示"。
private static boolean diagonalContains(char[][] grid,String word){
int wordLength = word.length();
char[] wordArray = word.toCharArray();
for(int i =0, length = grid.length; i < length; i++){
loop:for(int j =0, k = i, subLength = grid[i].length;
j < subLength && k >= wordLength; j++, k--){
for(int l =0; l < wordLength; l++){
if(grid[j + l][k - l]!= wordArray[l]){
continue loop;
}
return true;
}
}
}
}
该函数要求我返回值,虽然我没有,因此我无法运行代码。我试图将return语句放在代码的不同区域,但似乎都没有。 另外,我想知道代码是否有效用于练习目的?
答案 0 :(得分:0)
基本上,有两个问题 1.如果返回类型不为空,则每个函数都应返回一些值。在您的情况下,仅在满足条件时指定返回值。你应该返回false,否则。
private static boolean diagonalContains(char[][] grid,String word){
int wordLength = word.length();
char[] wordArray = word.toCharArray();
for(int i =0, length = grid.length; i < length; i++){
loop:for(int j =0, k = i, subLength = grid[i].length;
j < subLength && k >= wordLength; j++, k--){
for(int l =0; l < wordLength; l++){
if(grid[j + l][k - l]!= wordArray[l]){
continue loop;
}
return true;
}
}
}
return false;
}
import java.util.*; class WordDiagonal{ public static void main(String[] args){ char grid[][] = {{'a','b','c'},{'d','e','f'},{'g','h','i'}}; if(checkDiagonalSubstring(grid,"aei")){ System.out.println("Contains.."); }else{ System.out.println("Sorry..!"); } } private static boolean checkDiagonalSubstring(char[][] grid, String word){ String diagonalString = ""; Integer i = 0; for(char[] charArray : grid){ diagonalString += charArray[i++]; } if(diagonalString.contains(word)){ return true; } return false; } }