最长公共子串

    xiaoxiao2024-12-26  81

    题目描述:

    有两个字符串(可能包含空格),请找出其中最长的公共连续子串,输出其长度。

    输入描述:

    给定两行字符串(长度在1000以内)

    输出描述:

    输出这两个字符串的最长公共连续子串的长度。

    输入样例:

    abcde bcd

    输出样例:

    3

    解题思路:

    一个简单的动态规划问题。设ans为最长公共连续子串的长度,用cnt来临时记录公共连续子串的长度。当str1和str2的字符相等就循环累加,不断更新ans最后输出即可。

    AC代码: 

    #include <bits/stdc++.h> using namespace std; int main() { string str1,str2; getline(cin,str1); getline(cin,str2); int ans = 0, cnt = 0; //ans为最大公共连续子串的长度 for(int i = 0; i < str1.length(); i++) { for(int j = 0; j < str2.length(); j++) { cnt = 0; int k = i; while(str1[k] == str2[j]) //相等就循环累加 { cnt++; k++; j++; } ans = max(ans,cnt); //ans取最大值 } } cout << ans << endl; return 0; }

     

    最新回复(0)