版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/90575252
有两个字符串(可能包含空格),请找出其中最长的公共连续子串,输出其长度。
给定两行字符串(长度在1000以内)
输出这两个字符串的最长公共连续子串的长度。
abcde bcd
3
一个简单的动态规划问题。设ans为最长公共连续子串的长度,用cnt来临时记录公共连续子串的长度。当str1和str2的字符相等就循环累加,不断更新ans最后输出即可。
#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; }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句