Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
substring-with-concatenation-of-all-words.py 2.58 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-12-30 21:04 +08:00 . remove semicolons
# Time: O((m + n) * k), where m is string length, n is dictionary size, k is word length
# Space: O(n * k)
import collections
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
result, m, n, k = [], len(s), len(words), len(words[0])
if m < n*k:
return result
lookup = collections.defaultdict(int)
for i in words:
lookup[i] += 1 # Space: O(n * k)
for i in xrange(k): # Time: O(k)
left, count = i, 0
tmp = collections.defaultdict(int)
for j in xrange(i, m-k+1, k): # Time: O(m / k)
s1 = s[j:j+k] # Time: O(k)
if s1 in lookup:
tmp[s1] += 1
if tmp[s1] <= lookup[s1]:
count += 1
else:
while tmp[s1] > lookup[s1]:
s2 = s[left:left+k]
tmp[s2] -= 1
if tmp[s2] < lookup[s2]:
count -= 1
left += k
if count == n:
result.append(left)
tmp[s[left:left+k]] -= 1
count -= 1
left += k
else:
tmp = collections.defaultdict(int)
count = 0
left = j+k
return result
# Time: O(m * n * k), where m is string length, n is dictionary size, k is word length
# Space: O(n * k)
class Solution2(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
result, m, n, k = [], len(s), len(words), len(words[0])
if m < n*k:
return result
lookup = collections.defaultdict(int)
for i in words:
lookup[i] += 1 # Space: O(n * k)
for i in xrange(m+1-k*n): # Time: O(m)
cur, j = collections.defaultdict(int), 0
while j < n: # Time: O(n)
word = s[i+j*k:i+j*k+k] # Time: O(k)
if word not in lookup:
break
cur[word] += 1
if cur[word] > lookup[word]:
break
j += 1
if j == n:
result.append(i)
return result
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助