JAVA beat 96.92 EASY TO UNDERSTAND SOLUTION


  • 0
    A

    public class Solution {

    public boolean validWordSquare(List<String> words) {
        int n = words.size();
        char[][] arr = new char[n][n];
        for(int i = 0; i < n; i++){
            String s = words.get(i);
            if(s.length() > n)
                return false;
            for(int j = 0; j < n; j++){
                if(j < s.length())
                    arr[i][j] = s.charAt(j);
                else
                    arr[i][j] = '0';
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(arr[i][j] != arr[j][i]){
                    return false;
                }
            }
        }
        return true;
    }
    

    }
    Create a int[][] 2D array---arr. with size nxn with n equal to the size of the words.
    Go via each string, 1. if the length of the string is larger than n, then return false;
    2. check arr[i][j] and arr[j][i] to see if they are same of not. if not, return false;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.