代码拉取完成,页面将自动刷新
# Time: O(n * l), n is the length of S, l is the average length of words
# Space: O(t) , t is the size of trie
import collections
import functools
class Solution(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for i, word in enumerate(words):
functools.reduce(dict.__getitem__, word, trie).setdefault("_end")
lookup = [False] * len(S)
for i in xrange(len(S)):
curr = trie
k = -1
for j in xrange(i, len(S)):
if S[j] not in curr:
break
curr = curr[S[j]]
if "_end" in curr:
k = j
for j in xrange(i, k+1):
lookup[j] = True
result = []
for i in xrange(len(S)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(S[i])
if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)
# Time: O(n * d * l), l is the average length of words
# Space: O(n)
class Solution2(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
lookup = [0] * len(S)
for d in words:
pos = S.find(d)
while pos != -1:
lookup[pos:pos+len(d)] = [1] * len(d)
pos = S.find(d, pos+1)
result = []
for i in xrange(len(S)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(S[i])
if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。