简体   繁体   中英

Find a specific word(diagonally) in 2D matrix

"Given a 2D char array and a string.

find if the specific string appears diagonally in the matrix".

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;
            }
        }
    }
}

The function asks me to return value, although I did, thus I am not able to run the code. I've tried to put return statement in different regions of the code but none seems to be working. Plus I would like to know if the code is efficient for the purpose of the exercise?

Basically, there are two problems
1. Every function should return some value, if the return type is not void. In your case, a return value is specified only if the criteria is satisfied. You are supposed to return false, otherwise.

  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;
  }
  1. The code seems to be inefficient and the logic seems to be wrong. So try the following code.
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;
      }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM