最长公共子串_牛客题霸_牛客网 (nowcoder.com)
给了两个字符串,要找到两个字符串的最长公共子串
"1AB2345CD","12345EF"
"2345"
class Solution {
public:
string LCS(string str1, string str2) {
//dp[i][j]表示到str1第i个个到str2第j个为止的公共子串长度
vector<vector<int> > dp(str1.length() + 1, vector<int>(str2.length() + 1, 0));
int max = 0;
int pos = 0;
for(int i = 1; i <= str1.length(); i++){
for(int j = 1; j <= str2.length(); j++){
//如果该两位相同
if(str1[i - 1] == str2[j - 1]){
//则增加长度
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else{
//该位置为0
dp[i][j] = 0;
}
//更新最大长度
if(dp[i][j] > max){
max = dp[i][j];
pos = i - 1;
}
}
}
return str1.substr(pos - max + 1, max);
}
};
遍历从1开始,dp数组的第0行和第0列都是用来存放空字符串的情况的,即dp[0][j]和dp[i][0]都表示其中一个字符串为空的情况,此时LCS长度为0。因此在遍历时,需要从1开始遍历,跳过这个特殊情况。
因为他要的是字符串嘛,需要更新情况就找最大长度字符串