Leetcode 422: Valid Word Square

问题描述:
Given an array of strings words, return true if it forms a valid word square.
A sequence of strings forms a valid word square if the kth row and column read the same string, where 0 <= k < max(numRows, numColumns).

解释说明:
这道题题面暗示了用二维数组,但其实不必真正构建二维数组。
但是牺牲空间可以降低编写代码的难度,所以在这里构建二维数组
把第i个字符串填写到matrix的第i行。填写完成后,如果matrix的第k行等于第k列(对于所有k),则返回真。

思路:
构建二维数组是最容易的方法。二维数组的行数就是list中字符串个数;二维数组的列数等于最长的字符串的长度(可能导致有些列填不满)。对于填写完的matrix,我们需要遍历数组,从而判断matrix(i,j) 和matrix(j,i) 是否相等。这里需要特别注意的一点,也是我犯的错误:矩阵不一定是正方形的。所以当我们读到 matrix(i,j)时,我们首先要判断matrix(j,i)是否存在。如果matrix(j,i)本身就不存在 (比如说2*5这种细长条的matrix),我们要首先排除它(返回假);基于matrix(j,i)存在,我们即可安全地判断matrix(i,j) 是否等于matrix(j,i),从而下结论

代码如下:

class Solution {
    public boolean validWordSquare(List<String> words) {
        //step1: calculate the longest word to form the matrix
        int counter=0;
        int sizeOfList=words.size();
        for(int i=0; i<sizeOfList; i++){
            counter=Math.max(words.get(i).length(),counter);
        }
        //step2: form the matrix
        char[][] matrix=new char[sizeOfList][counter];
        //step3: fill the matrix
        for(int i=0; i<sizeOfList; i++){
            int length=words.get(i).length();
            for(int j=0; j<length; j++){
                matrix[i][j]=words.get(i).charAt(j);
            }
        }
        //step4: check if the matrix is a square matrix
        for(int i=0; i<sizeOfList; i++){
            for(int j=0; j<words.get(i).length(); j++){
                //case 1: return false if (j,i) does not exist
                if((j>sizeOfList-1)||(i>counter-1)){
                    return false;
                }
                //case 2: (j,i) exists (including ' ') but does not match 
                if(matrix[i][j]!=matrix[j][i]){
                    return false;
                }
            }
        }
        return true;
    }
}

时间复杂度: O(m*n), m是list中字符串个数,n是最长的字符串的长度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值