算法之字符串公共子串的计算

 

 分析和思路:

双重循环判断字符是否相等,相等即进入循环,注意退出循环后,要把索引回退到新的位置

 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 }

 

posted @ 2022-03-04 22:14  技术笔记记录  阅读(58)  评论(0)    收藏  举报