1 //比较两个字符串大小 2 bool compareSub(char* const s1,char* const s2) 3 { 4 int i=0; 5 while((i<strlen(s1))&&(i<strlen(s2))) 6 { 7 if(toupper(s1[i])<toupper(s2[i])) 8 return true; 9 else if(toupper(s1[i])>toupper(s2[i])) 10 return false; 11 ++i; 12 } 13 return strlen(s1)>strlen(s2); 14 } 15 16 //比照两个字符串的公共子串 17 int commonSub(char* s1,char* s2,char* comChar) 18 { 19 int i=0; 20 while((i<strlen(s1))&&(i<strlen(s2))) 21 { 22 if(toupper(s1[i])==toupper(s2[i])) 23 { 24 comChar[i]=s1[i]; 25 ++i; 26 } 27 else 28 break; 29 } 30 comChar[i]='\0'; 31 return i; 32 } 33 //获得最长公共子串 34 int getLongestSub(char* c,char* subChar) 35 { 36 vector<char*> subVector; 37 //获得子串 38 for(int i=0;i<strlen(c);i++) 39 { 40 subVector.push_back(&c[i]); 41 } 42 //子串排序 43 sort(subVector.begin(),subVector.end(),compareSub); 44 //获得最长子串 45 const int n=strlen(c); 46 char* tempChar=new char[n]; 47 int max=0; 48 for(int i=0;i<subVector.size()-1;i++) 49 { 50 int temp=commonSub(subVector.at(i),subVector.at(i+1),tempChar); 51 if(temp>max) 52 { 53 max=temp; 54 strcpy(subChar,tempChar); 55 } 56 } 57 delete[] tempChar; 58 return max; 59 } 60 61 //简单示范 62 int main() 63 { 64 //输入 65 char* c=new char[100]; 66 cin.getline(c,100); 67 char* subChar=new char[100]; 68 int max=0; 69 max=getLongestSub(c,subChar); 70 //输出 71 cout<<"biggest substring of <"<<c<<">"<<endl; 72 cout<<"length:"<<max<<" subString:"<<subChar<<endl; 73 delete[] subChar; 74 delete[] c; 75 system("pause"); 76 }