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"]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值