您将得到一个字符串和一个有效单词列表(所有字母都是小写)。请编写一个函数,判断字符串是否由列表中的一个或多个单词组成。
题目难度:中等
题目来源:codewars
def valid_word(word, li):
pass
assert valid_word('hogwarts', ['hog', 'warts']) is True
assert valid_word('hogwarts', ['warts', 'hog']) is True
assert valid_word('hogwarts', ['war','ts', 'hog']) is True
assert valid_word('hogwarts', ['h','o','g','w','a','r','t','s']) is True
assert valid_word('hogwarts', ['hog', 'wart']) is False
assert valid_word('hogwarts', ['hogw', 'warts']) is False
def valid_word(word, li):
my_dict = {} # 存储子串及子串出现的位置
for item in li:
try:
my_dict[item] = word.index(item)
except: # index函数找不到子串时会报异常
return False
# 按子符串出现的位置对字典进行排序
sorted_list = sorted(my_dict.items(), key = lambda kv:(kv[1], kv[0]))
print(sorted_list)
now_idx = 0
# 检查字符串拼接是否正确
for i in range(len(sorted_list)-1):
now_idx += len(sorted_list[i][0])
if now_idx != sorted_list[i+1][1]:
return False
return now_idx+len(sorted_list[-1][0]) == len(word)
assert valid_word('hogwarts', ['hog', 'warts']) is True
assert valid_word('hogwarts', ['warts', 'hog']) is True
assert valid_word('hogwarts', ['war', 'ts', 'hog']) is True
assert valid_word('hogwarts', ['h', 'o', 'g', 'w', 'a', 'r', 't', 's']) is True
assert valid_word('hogwarts', ['hog', 'wart']) is False
assert valid_word('hogwarts', ['hogw', 'warts']) is False
会不会有下面这种断言
assert valid_word(‘hogwarts’, [‘hogw’,‘hog’,‘warts’]) is True
你这个用例不会,但如果是valid_word(‘hoghogwarts’, [‘hog’, ‘warts’, ‘hog’])这样子的就不行了