2025-02-11 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 11
Description
Remove All Occurrences of a Substring
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:
Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". - s = "dababc", remove "abc" starting at index 3, so s = "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 so s = "axxxyyyb". - s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". - s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". - s = "axyb", remove "xy" starting at index 1 so s = "ab". Now s has no occurrences of "xy".
Constraints:
1 <= s.length <= 1000
1 <= part.length <= 1000
s
andpart
consists of lowercase English letters.
Solution
class Solution {
public:
string removeOccurrences(string s, string part) {
string answer;
int sz = 0;
int len = part.length();
for(auto c : s) {
answer.push_back(c);
sz += 1;
if(sz >= len && answer.ends_with(part)) {
sz -= len;
answer.resize(sz);
}
}
return answer;
}
};
// Accepted
// 80/80 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 13.98 % of cpp submissions (9.6 MB)