暴力法:提供了一个删除指定字符串的方法 substr(pos, len)
保留从pos往后len长度的字符串
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string removeOccurrences(string s, string part) {
int m = part.size();
string res;
for (const char ch : s){
// 模拟从左至右匹配的过程
res.push_back(ch);
int n = res.size();
if (n >= m && res.substr(n - m, n) == part){// s.substr(pos, len)如果(n-m)到n和part一样
// 如果匹配成功,那么删去对应后缀
res = res.substr(0, n - m);//把0到(n-m)的字符串保留下来 剩下舍去
}
}
return res;
}
};
int main(){
string s = "daabcbaabcbc";
string part = "abc";
Solution a;
string res=a.removeOccurrences(s,part);
for (char a : res){
cout << a;
}
system("pause");
return 0;
}