第一篇博客
word-break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s =‘leetcode’,
dict =[‘leet’, ‘code’].
Return true because ‘leetcode’ can be segmented as ‘leet code’.
题意
即判断字符串s能否被切割成列表dict中的元素
思路
使用的是dp来解决,因为不需要枚举每一种可能出来,只是求true or false, 采用dp最有效率
python实现
class Solution:
def word_break(self, s, dict):
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
# 注意,range(i+1)中下标的目的是为了方便以后取到i本身
for i in range(n):
for j in range(i+1):
# print(j, i)
# dp[j]实际上是前一个,不要混淆dp与s的下标
# s[j: i+1]就取到了i本身
if dp[j] and s[j: i+1] in dict:
dp[i+1] = True
return dp[n]
if __name__ == '__main__':
s = 'leetcode'
# print(s[7:8])
dict = ['leet', 'code']
so = Solution()
print(so.word_break(s, dict))