题目
【中等】【dp】最长公共子串
描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
思路
- 使用dp[i][j]记录str1中以第i个字符结尾的子串/str2中以第j个字符结尾的公共子串长度
- 遍历两字符串的字符,若相同,则当前长度等于前一位的长度+1,即dp[i][j] = dp[i-1][j-1]+1 ;若不同,则当前长度置为0
- 每次更新dp[i][j]后,维护最大值和最大子串结束的位置
- 最后根据最大值和结束位置来截取出最长公共子串
代码
class Solution {
public:
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
string LCS(string str1, string str2) {
// write code here
//dp[i][j]表示str1以第i个结尾/str2以第j个结尾的公共子串长度
vector<vector