两个字符串的最长公共子串(C++)
生活随笔
收集整理的這篇文章主要介紹了
两个字符串的最长公共子串(C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:輸入兩個字符串,找到兩個字符串中最長的公共字符字串
輸入:cdeg abcdefg
輸出:cde
思路:肯定是從長度較小的字符串作為第一層循環
本題需要用動態規劃求解,dp[i][j]記錄短字符串 s1 前 i 個字符和長字符串 s2 前 j 個字符的最長子串的長 ,初始化所有值為 0。當 s1[i-1] = s2[j-1]時,dp[i][j] = dp[i - 1][j - 1] + 1
這里使用一個額外的值 start 來記錄最長子串在短字符串 s1 中出現的起始位置,maxlen記錄當前最長子串的長度,當dp[i][j] > maxlen 時,maxlen = dp[i][j], 則start = i - maxlen ;s1[i-1] != s2[j-1]時不需要任何操作,最后獲取 substr(start, maxlen)即為所求。
#include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std;int main(){ string str1, str2; while (cin >> str1 >> str2){ //以最短的字符串作為s1 if (str1.size() > str2.size()){swap(str1, str2);} int len1 = str1.size(), len2 = str2.size(); int start = 0, max = 0;vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0)); //(len1+1,len2+1) for (int i = 1; i <= len1; i++){for (int j = 1; j <= len2; j++){if (str1[i - 1] == str2[j - 1]){dp[i][j] = dp[i - 1][j - 1] + 1;}//如果有更長的公共子串,更新長度 if (dp[i][j] > max){max = dp[i][j];//以i結尾的最大長度為max, 則子串的起始位置為i - max start = i - max; } } }cout << str1.substr(start, max) << endl;}return 0; }不得不說,這位大佬寫得清晰明了,也不是參考,是copy,我自己看
參考:https://blog.csdn.net/qq_44770155/article/details/98261973?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_title~default-12.control&spm=1001.2101.3001.4242
總結
以上是生活随笔為你收集整理的两个字符串的最长公共子串(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Duplicate的一点总结
- 下一篇: 消息传输协议-MQTT篇-QoS