字符串问题---替换字符串中连续出现的指定字符串

【题目】

  给定三个字符串str,from和to,已知from字符串中没有重复字符,把str中所有from的子串全部替换成to字符串,对连续出现from的部分要求只替换一个to字符串,返回最终的结果字符串。

【举例】

  str = “123abc”,from = “abc”,to = “4567”,返回“1234567”。
  str = “123”,from = “abc”,to = “4567”,返回“123”。
  str = “123abcabc”,from = “abc”,to = “X”,返回“123X”。

【基本思路】

  1. 使用变量match表示目前匹配到from的什么位置。从左到右遍历str。

  2. 如果str[i] == from[match],并且match是from的最后一个字符的位置,说明在str中发现了from的子串,将该子串字符的位置全部设置为空字符。同时将match归0,继续遍历数组。如果match不是from的最后位置,match + 1。

  3. 如果str[i] != from[match],将match归0,同时,还需要注意此时str[i]是否等于from[0],如果等于的话,说明str[i]可能作为下一处子串的开头,令match + 1。

  4. 接下来只需要把空字符的位置替换成to即可,连续的空字符只替换一次。

下面是使用python3.5实现的代码

#替换字符串中连续出现的指定字符串
def replace(str1, fro, to):
    if str1 == None or fro == None or to == None  or str1 == '' or fro == '':
        return str1
    chas = list(str1)
    match = 0
    for i in range(len(str1)):
        if chas[i] == fro[match]:
            match += 1
            if match == len(fro):
                index = i
                while match > 0:
                    chas[index] = ''
                    index -= 1
                    match -= 1
        else:
            match = 0
            if chas[i] == fro[0]:   #如果相等,从当前字符重新匹配
                match += 1
    cur = ''
    res = ''
    for i in range(len(str1)):
        if chas[i] != '':
            cur = cur + chas[i]
        else:
            if i == 0 or chas[i-1] != '':
                res = res + cur + to
                cur = ''
    if cur != '':
        res += cur
    return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值