题解 | 公共子串计算
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
//首先建立一张二维表格,行为较短的字符串str1,列为较长的字符串str2,使用两层for循环遍历两个字符串,当遍历到第一次长字符串与短字符串的元素相同时,沿着对角线遍历,同时计数器+1,否则计数器清零(只要不是沿着对角线遍历,计数器就要清零,防止对角线末位与下一次遍历连续),max取计数器最大的值 #include <iostream> #include <string> using namespace std; int main() { string str1, str2; getline(cin, str1); getline(cin, str2); if (str1.length() > str2.length()) { swap(str1, str2); //交换两个字符串的值,保证str1是比较短的 } int max = 0; int len = 0; for (int i=0 ; i < str1.length() ; i++) { for (int j=0 ; j < str2.length() ; j++) { len = 0;//二维表格中重新按列开始遍历时,清零一次 if (str1[i] == str2[j] && i < str1.length() && j < str2.length()) {//表格中找到第一次长字符串与段字符串相等的字母时,开始按照对角线遍历 int ti = i; int tj = j; while (str1[ti] == str2[tj] && ti < str1.length() && tj < str2.length()) {//按照对角线判断长字符串字符与短字符串字符是否相等 len ++; ti++; tj++; } if (max < len) { max = len;//取公共子串的最大值 } } } } cout << max; } // 64 位输出请用 printf("%lld")