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
part
and 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 <= 1000
1 <= part.length <= 1000
s
andpart
consists 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
个字符原理是一样的,只不过这道题目消除的是子串,消除的逻辑不同。之前的题目是通过统计数字来消除,而这道题目是通过对比子串消除。。这道题目的分享到这里,感谢你的支持!