字符串前后缀(包含拼接)
最长前缀
#include<cstring> #include<iostream> #include<string> using namespace std; int main() { string s1,s2; char s[10000]; while(cin >> s1 >> s2) { int flag = 0; int len = s1.size(); if(s2.size() < len) len = s2.size() ; for(int i = 0;i< len;++i) { if(s1[i] == s2[i]) { s[i] = s1[i]; flag = 1; } else break; } if(flag) cout << "The common prefix is " << s << endl; else cout << "No common prefix" << endl; } return 0; }
一个字符串的前缀和另一个字符串的后缀
#include<cstdio> #include<cstring> using namespace std; const int maxn=1e5+10; void cal_next(char* str,int* next,int len) { next[0]=next[1]=0; for(int i=1;i<len;++i) { int j=next[i]; while(j&&str[i]!=str[j]) j=next[j]; next[i+1]=(str[j]==str[i])?j+1:0; } } int kmp(char *str,int slen,char *ptr,int plen) { int next[maxn]; cal_next(ptr,next,plen); int j=0; for(int i=0;i<slen;i++) { while(j&&ptr[j]!=str[i]) j=next[j]; if(ptr[j]==str[i]) ++j; } return j; } char str[maxn],ptr[maxn],ans[maxn]; int main() { while(scanf("%s%s",str,ptr)!=EOF){ int plen=strlen(ptr),slen=strlen(str); int len=kmp(str,slen,ptr,plen); if(len==0) printf("0\n"); else{ memset(ans,0,sizeof(ans)); memcpy(ans,ptr,len*sizeof (char)); printf("%s %d\n",ans,len); } } return 0; }
-
riemanmarjorie-> rie 3