KMP

    xiaoxiao2022-07-13  165

    一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?

    Input 输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。 Output 输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。 Sample Input abcde a3 aaaaaa aa # Sample Output 0 3 #include <iostream> #include <string> #include <vector> using namespace std; void CalNext(vector<int>& next, string temp) { // 独创计算next数组的方法 int move = 1, i = 1, match = 0; while (i < temp.size()) { while (match + move <= i) { if (temp[match] == temp[match + move]) match++; else { match = 0; move++; } } i++; next.push_back(match); } return; } void KMP(string& s, string& temp, vector<int>& next) { int i = 0, j = 0, num = 0; while (i < s.size()) { if (s[i] == temp[j]) { i++; j++; } else { if (j == 0) i += 1; else i += j - next[j - 1]; //跳转方式 j = 0; } if (j == temp.size()) { j = 0; num++; } } cout << num << endl; } int main() { string s; while (cin >> s) { if (s == "#") { break; } string temp; cin >> temp; int num = 0; if (temp.size() == 1) { for (int i = 0; i < s.size(); i++) if (s[i] == temp[0]) num++; cout << num << endl; } else{ vector<int> next; next.push_back(-1); CalNext(next, temp); KMP(s, temp, next); } } return 0; }
    最新回复(0)