题意:给你一个字符串 ,问你既是它的前缀 ,又是它的后缀,且是在中间出线过的最长字串是什么
解题思路:KMP变形,不熟悉next写出来还是有点困难
解题代码:
1 // File Name: 126b.cpp 2 // Author: darkdream 3 // Created Time: 2015年03月07日 星期六 15时23分51秒 4 5 #include<vector> 6 #include<list> 7 #include<map> 8 #include<set> 9 #include<deque> 10 #include<stack> 11 #include<bitset> 12 #include<algorithm> 13 #include<functional> 14 #include<numeric> 15 #include<utility> 16 #include<sstream> 17 #include<iostream> 18 #include<iomanip> 19 #include<cstdio> 20 #include<cmath> 21 #include<cstdlib> 22 #include<cstring> 23 #include<ctime> 24 #define LL long long 25 26 using namespace std; 27 char str[1000005]; 28 int dp[1000005]; 29 int hs[1000005]; 30 void getnext(char *p,int next[]) 31 { 32 int pLen =strlen(p); 33 next[0] = -1; 34 int k = -1; 35 int j = 1; 36 while(j < pLen ) 37 { 38 if(k == -1 || p[j] == p[k+1]) 39 { 40 if(p[j] == p[k+1]) 41 { 42 next[j] = k + 1; 43 k ++; 44 j ++ ; 45 }else{ 46 next[j] = -1; 47 j++; 48 } 49 } 50 else { 51 k = next[k] ; 52 } 53 } 54 } 55 int main(){ 56 scanf("%s",str); 57 getnext(str,dp); 58 int len = strlen(str); 59 for( int i = 0;i < len; i++) 60 { 61 /*if(dp[i] == 0 && str[i] == str[0]) 62 { 63 64 } 65 else 66 dp[i]--; 67 *///printf("%d ",dp[i]); 68 if(dp[i] != -1) 69 hs[dp[i]] ++; 70 } 71 if(dp[len-1] != -1) 72 hs[dp[len-1]] -- ; 73 while(hs[dp[len-1]] ==0 && dp[len-1] != -1) 74 { 75 // printf("dp[len-1] = %d ",dp[len-1]); 76 dp[len-1] = dp[dp[len-1]]; 77 } 78 // printf("ans = %d ",dp[len-1]); 79 int an = 0 ; 80 for(int i = len -2;i >= 1;i --) 81 if(dp[i] == dp[len -1]) 82 { 83 an = 1 ; 84 } 85 if(an == 0 || dp[len -1] == -1 || (dp[len-1] ==0 && str[len-1] != str[0])) 86 { 87 printf("Just a legend "); 88 return 0 ; 89 } 90 for(int i =0 ;i <= dp[len-1];i ++) 91 printf("%c",str[i]); 92 93 return 0; 94 }