15ms JAVA


  • 1
    Q

    compare the matrix in the method shown below

    Only compare the string in bold each iteration

    a b c d
    b
    c
    d

    a b c d
    b e f g
    c f
    d g

    a b c d
    b e f g
    c f h
    d g

    public class Solution {
        public boolean validWordSquare(List<String> words) {
            int h = words.size();
            if (h == 0) {
                return true;
            }
            int row = 0, col = 0;
            while (row < h) {
                String ts = words.get(row);
                if (col >= ts.length()) {
                   for (int i = row+1; i < h; ++i) {
                        String tvStr = words.get(i);
                        if (col < tvStr.length()) {
                            return false;
                        }
                    }
                    return true;
                }
                String hStr = ts.substring(col);
                StringBuilder vStr = new StringBuilder();
                for (int i = row; i < h; ++i) {
                    String tvStr = words.get(i);
                    if (col < tvStr.length()) {
                        vStr.append(tvStr.charAt(col));
                    } else {
                        break;
                    }
                }
                if (!hStr.equals(vStr.toString())) {
                    return false;
                }
                row++;
                col++;
            }
            return true;
        }
    }

Log in to reply
 

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