如何实现反转句子指定次数出现的子串,现有遍历逻辑出错该如何修复?
问题解决实现
核心思路
利用Python字符串find()方法的起始位置参数,每次匹配到目标子串后,从子串结束的位置继续向后搜索,无需从头遍历整个句子,避免重复匹配错误。
可运行实现代码
def reverse_nth_occurrence(sentence: str, word: str, occurrence: int | str) -> str: occurrence = int(occurrence) # 基础校验 if not word or occurrence < 1: return sentence res = [] # 当前搜索起始位置 start = 0 count = 0 word_len = len(word) while True: # 从start位置开始搜索子串 idx = sentence.find(word, start) if idx == -1: # 找不到剩余子串,把剩下的内容拼进去 res.append(sentence[start:]) break count += 1 # 把当前匹配位置之前的内容拼进去 res.append(sentence[start:idx]) if count == occurrence: # 是第n次出现,拼反转后的子串 res.append(word[::-1]) else: # 不是,拼原串 res.append(word) # 更新下一次搜索的起始位置 start = idx + word_len # 错误提示 if count == 0: print('could not find the word') return sentence if count < occurrence: print(f"no such occurrence: 目标子串仅出现{count}次,不足{occurrence}次") return sentence return ''.join(res) # 测试用例 sentence = 'Dani likes bananas, Dani also likes apples' word = 'lik' occurrence = '2' print(reverse_nth_occurrence(sentence, word, occurrence)) # 输出:Dani likes bananas, Dani also kiles apples
原代码问题说明
原代码存在嵌套循环逻辑错误:外层遍历子串的每个字符,内层每次都从头遍历整个句子,且没有记录上一次匹配结束的位置,导致每次循环都会从头开始匹配,出现匹配到无关字符的问题。
内容的提问来源于stack exchange,提问作者Dvir Iluz
相关产品推荐
相关产品推荐

