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.
Example 1:
1 | Input: s = "daabcbaabcbc", part = "abc" |
Example 2:
1 | Input: s = "axxxxyyyyb", part = "xy" |
Constraints:
1 <= s.length <= 10001 <= part.length <= 1000sandpartconsists of lowercase English letters.
Analysis
这道题目给出一个字符串s以及一个模式part,要求当字符串存在子串和part一样时,就消除掉,问最后剩下的部分是什么。这道题目消除连续k个相同的字符串是一个道理,有两个下标实现一个类似stack的逻辑。下标i为快下标,用来遍历s,另一个下标j为慢下标,用来维护剩余的字符串到哪里了。每次检查substr(j - m, m)是否和part相等,m是part的长度,如果相等则回退j。最后j指向的位置就是结果的位置。
Solution
无。
Code
1 | class Solution { |
Summary
这道题目和之前消除连续k个字符原理是一样的,只不过这道题目消除的是子串,消除的逻辑不同。之前的题目是通过统计数字来消除,而这道题目是通过对比子串消除。。这道题目的分享到这里,感谢你的支持!