1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
find-and-replace-in-string.py 1.30 KB
一键复制 编辑 原始数据 按行查看 历史
# Time: O(n + m), m is the number of targets
# Space: O(n)
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
bucket = [None] * len(S)
for i in xrange(len(indexes)):
if all(indexes[i]+k < len(S) and S[indexes[i]+k] == sources[i][k]
for k in xrange(len(sources[i]))):
bucket[indexes[i]] = (len(sources[i]), list(targets[i]))
result = []
i = 0
while i < len(S):
if bucket[i]:
result.extend(bucket[i][1])
i += bucket[i][0]
else:
result.append(S[i])
i += 1
return "".join(result)
# Time: O(mlogm + m * n)
# Space: O(n + m)
class Solution2(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
for i, s, t in sorted(zip(indexes, sources, targets), reverse=True):
if S[i:i+len(s)] == s:
S = S[:i] + t + S[i+len(s):]
return S
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

搜索帮助