难度: Medium
原题连接
内容描述
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
思路 1 - 时间复杂度: O(N^2)- 空间复杂度: O(N)******
beats 55.17%
ok[i]
tells whether s[:i]
can be built.
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
ok = [True]
for i in range(1, len(s)+1):
ok += [any(ok[j] and s[j:i] in wordDict for j in range(i))]
return ok[-1]
但是往list里面加数据的方法有快有慢,下面是对比:
>>> from timeit import timeit
>>> timeit('x.append(1)', 'x = []', number=10000000)
1.9880003412529277
>>> timeit('x += 1,', 'x = []', number=10000000)
1.2676891852971721
>>> timeit('x += [1]', 'x = []', number=10000000)
3.361207239950204
因此我们可以将代码直接换成下面的格式
ok += any(ok[j] and s[j:i] in wordDict for j in range(i)) # 会报错
但是这样会报错,TypeError: 'bool' object is not iterable,因此bool类型数据不能这样加,别的可以(list类型本身当然要注意哈)
因此在这个例子中我们这样:
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
ok = [True]
for i in range(1, len(s)+1):
ok += any(ok[j] and s[j:i] in wordDict for j in range(i)),
return ok[-1]
代码里面的那个逗号构建了一个tuple,也会快一点