1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.py 1.20 KB
一键复制 编辑 原始数据 按行查看 历史
# Time: O(n)
# Space: O(n)
class Solution(object):
def isPrefixOfWord(self, sentence, searchWord):
"""
:type sentence: str
:type searchWord: str
:rtype: int
"""
def KMP(text, pattern):
def getPrefix(pattern):
prefix = [-1] * len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j > -1 and pattern[j + 1] != pattern[i]:
j = prefix[j]
if pattern[j + 1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
prefix = getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j != -1 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
if j+1 == len(pattern):
return i-j
return -1
if sentence.startswith(searchWord):
return 1
p = KMP(sentence, ' ' + searchWord)
if p == -1:
return -1
return 1+sum(sentence[i] == ' ' for i in xrange(p+1))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助