Problem
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
- Find the leftmost occurrence of the substring
partand remove it froms.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/
Example 1:
Input:
s = "daabcbaabcbc", part = "abc"
Output:"dab"
Explanation: The following operations are done:
s = "daabcbaabcbc", remove"abc"starting at index 2, sos = "dabaabcbc".s = "dabaabcbc", remove"abc"starting at index 4, sos = "dababc".s = "dababc", remove"abc"starting at index 3, sos = "dab".Now s has no occurrences of
"abc".
Example 2:
Input:
s = "axxxxyyyyb", part = "xy"
Output:"ab"
Explanation: The following operations are done:
s = "axxxxyyyyb", remove"xy"starting at index 4 sos = "axxxyyyb".s = "axxxyyyb", remove"xy"starting at index 3 sos = "axxyyb".s = "axxyyb", remove"xy"starting at index 2 sos = "axyb".s = "axyb", remove"xy"starting at index 1 sos = "ab".Now s has no occurrences of
"xy".
Constraints:
1 <= s.length <= 10001 <= part.length <= 1000s andpartconsists of lowercase English letters.
Test Cases
1 | class Solution: |
1 | import pytest |
Thoughts
可以看作是 3174. Clear Digits 的进阶版,待匹配的 pattern 从两个字符(一个字母+一个数字)变成任意长度的字符串。
处理方法也类似,用一个栈记录结果字符串的字符。遍历 s,对于每个字符,先入栈,然后对比栈顶 m 个字符是否与 part 一致(设 part 的长度为 m),一致就把这些字符都弹出。
时间复杂度 O(n * m),空间复杂度 O(n)。
Code
1 | class Solution: |