LeetCode: Valid Word Square

Posted chenxp2311

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode: Valid Word Square相关的知识,希望对你有一定的参考价值。

这是 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.

示例如下:


个人还是喜欢用 python 实现,自己写的代码如下:

def validWordSquare(words):
    height = len(words)
    width = len(words[0])
    idx = 0
    for w in range(width):
        word_tmp = ""
        for h in range(height):
            if len(words[h]) > w:
                word_tmp = word_tmp + words[h][w]
            else:
                continue
        if words[w] == word_tmp:
            idx = idx + 1
            continue
        else:
            break
        print word_tmp
    if idx == width:
        return True
    else:
        return False

运行结果如下:


值得注意的是,在我的 python 代码中间,如果少了这么一句:

if len(words[h]) > w:
    word_tmp = word_tmp + words[h][w]
else:
    continue

没有长度的判断,直接写成:

word_tmp = word_tmp + words[h][w]

就会报如下错误:

因为对于输入的 list 是下面的话,w = 4 的值,就超出最后一个单词:dt 的范围了:

["abcd", "bnrt", "crm", "dt"]

以上是关于LeetCode: Valid Word Square的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode408. Valid Word Abbreviation

Leetcode: Valid Word Abbreviation

Valid Word Abbreviation Leetcode

LeetCode 409: Valid Word Abbreviation

LeetCode: Valid Word Square

leetcode408 - Valid Word Abbreviation - easy