3 条题解

  • 1
    @ 2025-2-15 14:10:56
    // https://dashoj.com/p/74
    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main() {
    	string text, pattren;
    	cin >> text >> pattren;
    	string str = pattren + '#' + text;
    	vector<int> pi(str.size(), 0);
    	for (int i = 1; i < str.size(); i++) {
    		int len = pi[i - 1];
    		while (len != 0 && str[i] != str[len]) len = pi[len - 1];
    		if (str[i] == str[len]) pi[i] = len + 1;
    	}
    	sort(pi.begin(), pi.end(), [](int a, int b) {
    		return a > b;
    	});
    	int cnt = 0, max = pi[0];
    	for (int i : pi) if (i == max) cnt++; else break;
    	cout << cnt << endl;
    	return 0;
    }
    
    • 1
      @ 2025-1-20 10:17:12

      直接使用find函数来查找字符串中的字串

      #include<bits/stdc++.h>
      using namespace std;
      int main() {
      	string c,s;
      	cin>>s>>c;
      	int index = 0;
          int sum = 0;
          while ((index = s.find(c,index)) != string::npos) {
            index ++;
            sum++;
          }
          cout << sum << endl;
          return 0;
      }
      
      • 1
        @ 2024-4-13 19:42:34

        kmp算法

        #include<cstdio>
        #include<iostream>
        using namespace std;
        
        const int N = 1e6 + 10;
        static int next_table[N];
        
        void nexttable(string s, int len) {
        	int p = 0, i = 1;
        	next_table[0] = 0;
        	while (i < len) {
        		if (s[i] == s[p]) {
        			p++;
        			next_table[i] = p;
        			i++;
        		}
        		else {
        			if (p != 0) {
        				p = next_table[p-1];
        			}
        			else {
        				next_table[i] = p;
        				i++;
        			}
        		}
        	}
        
        	for (int i = len - 1; i > 0; i--) next_table[i] = next_table[i - 1];
        	next_table[0] = -1;
        
        }
        
        int kmp(string bigs, string s, int len) {
        	int count = 0;
        	int m = bigs.length();
        	int i = 0, j = 0;
        	while (j < m) {
        		if (i == len - 1 && s[i] == bigs[j]) {
        			count++;
        			i = next_table[i];
        		}
        
        		if (s[i] == bigs[j]) {
        			i++; j++;
        		}
        		else {
        			if (next_table[i] == -1) {
        				j++;
        			}
        			else i = next_table[i];
        
        		}
        	}
        	return count;
        
        }
        
        int main() {
        	string bigs, s;
        	cin >> bigs >> s;
        	int len = s.length();
        	nexttable(s, len);
        
        	cout << kmp(bigs, s, len);
        	return 0;
        }
        
        • 1

        信息

        ID
        74
        时间
        1000ms
        内存
        256MiB
        难度
        8
        标签
        递交数
        516
        已通过
        64
        上传者