1. 程式人生 > 其它 >演算法之字串公共子串的計算

演算法之字串公共子串的計算

分析和思路:

雙重迴圈判斷字元是否相等,相等即進入迴圈,注意退出迴圈後,要把索引回退到新的位置

 1 #include "iostream"
 2 #include "string"
 3 
 4 using namespace std;
 5 
 6 
 7 
 8 
 9 
10 int main()
11 {
12     
13     string str1;
14     string str2;
15     while(cin>>str1>>str2)
16     {
17           int max_len=0;
18         if(str1.size()==0
||str2.size()==0) 19 { 20 cout<<0<<endl; 21 continue; 22 } 23 for(int i=0;i<str1.size();i++) 24 { 25 26 for(int j=0;j<str2.size();j++) 27 { 28 int count=0; 29 30
if(str1[i]==str2[j]) 31 { 32 while(i<str1.size()&&j<str2.size()&&str1[i]==str2[j]) 33 { 34 count++; 35 i++; 36 j++; 37 }
38 39 if(count>=max_len) 40 { 41 max_len=count; 42 } 43 i=i-count;//重要,此處需要回退 44 j=j-count; 45 } 46 47 } 48 49 } 50 cout<<max_len<<endl; 51 } 52 53 return 0; 54 }
主要為了自己學習