Description
给你两个串A,B,每次在B串中从左到右找串A,并将该子串删除,直到找不到为止,问你能删几次。
Input
两行每行一个字符串分别代表A,B串。
Output
一行一个整数表示删的次数。
abc
abcabcabaabcbccc
-
Sample Input
5
-
Sample Output
HINT
样例解释:
abcabcabaabcbccc-> abcabaabcbccc-> abaabcbccc-> ababccc-> abcc-> c
共5次。
数据范围:
对于20%的数据 length(B)<1000
对于50%的数据 length(B)<100000
对于100%的数据 0
Updated By MCHacker
这一题貌似暑假时某神犇学长讲过......
直接每次压栈后如果栈顶的几个元素正好是要消除的字符串,就直接出栈
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
const int MAXN = 10000010;
int c[MAXN];
int main() {
string a, b; cin >> b >> a;
int res = 0, top = 0, sa = a.size(), sb = b.size();
for (int i=0; i<sa; ++i) {
c[++top] = a[i];
if (top<sb) continue;
if (a[i]!=b[sb-1]) continue; // 长度不够,不管
bool flag = true;
for (int j=top-sb+1, k=0; j<top; ++j, ++k) { // 检查栈顶几个元素是不是要消除的字符串
if (c[j]!=b[k]) { // 不是,不管
flag = false; break;
}
}
if (flag) {
++res; top -= sb; // 栈顶元素出栈
}
}
printf("%d\n", res); // 输出结果
return 0;
}