Leetcode: Valid Word Square

Given a sequence of words, check whether it forms a valid word square.

A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).

Note:
The number of words given is at least 1 and does not exceed 500.
Word length will be at least 1 and does not exceed 500.
Each word contains only lowercase English alphabet a-z.

这题看起来简单但是其实很容易写错

本来想j 不从0开始,而是从 i+1开始检查,可以节省时间,但是一些为Null的情况会使讨论很复杂

比如

[
  "abcd",
  "bnrt",
  "crm",
  "dtz"
]
第三行检查到m就结束了,因为j<word.get(i).length(),所以第三行发现不了z的不同;第四行如果从index=4开始检查,就会漏检z的情况

综上,这种List<List<Integer>> 结构,两两比较,最好保证其中一个始终不为null,另一个为null就报错,这样可以省掉很多讨论情况
然后要保证一个始终不为null,就需要j<word.get(i).length(), 那么为了不漏检,j要从0开始
 1 public class Solution {
 2     public boolean validWordSquare(List<String> words) {
 3         if(words == null || words.size() == 0){
 4             return true;
 5         }
 6         
 7         for (int i=0; i<words.size(); i++) {
 8             for (int j=0; j<words.get(i).length(); j++) {
 9                 if (words.size()<=j || words.get(j).length()<=i || words.get(i).charAt(j)!=words.get(j).charAt(i))
10                     return false;
11             }
12         }
13         return true;
14     }
15 }
 
原文地址:https://www.cnblogs.com/EdwardLiu/p/6196207.html