本文主要是介绍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 = 0for w in range(width):word_tmp = ""for h in range(height):if len(words[h]) > w:word_tmp = word_tmp + words[h][w]else:continueif words[w] == word_tmp:idx = idx + 1continueelse:breakprint word_tmpif idx == width:return Trueelse: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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!