替换字符串中连续出现的指定字符串
替换连续字符串
【题目】
给定三个字符串s、old和new,
把s中所有old的子串全部替换成new字符串,对连续出现old的部分要求只替换成一个new字符串,返回最终的结果字符串。
【举例】
s=“123abc”,old=“abc”,new=“4567”,返回"1234567"。
s=“123”,old=“abc”,new=“456”,返回"123"。
s=“123abcabc”,old=“abc”,new=“X”,返回"123X"。
算法思路
连续出现的指定字符串只替换一次
指定字符串替换为连续的0,连续出现的指定字符串则也为连续的0
每次在第一次出现0时,将保留的字符串和替换字符串陆续拼接
相应代码
# 指定字符串为连续0
def clear(arr, end, length):
for i in range(length):
arr[end - i] = 0
# 替换连续字符串
def remove_continue_str(s, old, new):
if s is None or old is None or new is None or len(s) == 0 or len(old) == 0 or len(new) == 0:
return s
arr = list(s)
match = 0
# 指定字符串为0
for i in range(len(s)):
if s[i] == old[match]:
match += 1
if match == len(old):
clear(arr, i, len(old))
match = 0
else:
match = 0
res = ""
cur = ""
# 拼接替换字符串
for i in range(len(arr)):
if arr[i] != 0:
cur += arr[i]
# 第一次遇见0,只拼接一次
elif arr[i] == 0 and (i == 0 or arr[i - 1] != 0):
res += cur + new
cur = ""
# 最后拼接
res += cur
return res
# 简单测试
if __name__ == '__main__':
s = "123abc"
old = "abc"
new = "4567"
print(remove_continue_str(s, old, new)) # 1234567
s = "123"
old = "abc"
new = "456"
print(remove_continue_str(s, old, new)) # 123
s = "123abcabc"
old = "abc"
new = "X"
print(remove_continue_str(s, old, new)) # 123X
有任何疑问和建议,欢迎在评论区留言和指正!
感谢您所花费的时间与精力!