CF126B Password

思路:

kmp略作修改。

实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 const int MAXN = 1000005;
 5 int neXt[MAXN];
 6 
 7 void getNext(string s)
 8 {
 9     int n = s.length();
10     neXt[0] = -1;
11     int k = -1, j = 0;
12     while (j < n)
13     {
14         if (k == -1 || s[j] == s[k])
15         {
16             j++; k++;
17             neXt[j] = k;
18         }
19         else
20         {
21             k = neXt[k];
22         }
23     }
24 }
25 
26 bool kmp(string s, string p)
27 {
28     int i = 0, j = 0;
29     int m = s.length(), n = p.length();
30     while (i < m && j < n)
31     {
32         if (j == -1 || s[i] == p[j]) i++, j++;
33         else j = neXt[j];
34     }
35     if (j == n) return true;
36     return false;
37 }
38 
39 int main()
40 {
41     string str;
42     cin >> str;
43     str += ' ';
44     int n = str.length();
45     getNext(str);
46     int tmp = neXt[n - 1];
47     bool flg = false;
48     while (tmp)
49     {
50         if (kmp(str.substr(1, n - 3), str.substr(0, tmp)))
51         {
52             cout << str.substr(0, tmp) << endl;
53             flg = true;
54             break;
55         }
56         tmp = neXt[tmp];
57     }
58     if (!flg) cout << "Just a legend" << endl;
59     return 0;
60 }
原文地址:https://www.cnblogs.com/wangyiming/p/7258864.html