💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、豆包、星火、月之暗面及文生图、文生视频 广告
## [查找两个字符串a,b中的最长公共子串](https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506?tpId=37&&tqId=21288&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking) 查找两个字符串a,b中的最长公共子串。若有多个,输出在较短串中最先出现的那个。 注:子串的定义:将一个字符串删去前缀和后缀(也可以不删)形成的字符串。请和“子序列”的概念分开! 这篇博文写得非常好 https://blog.csdn.net/qq_25800311/article/details/81607168 ![](https://img.kancloud.cn/be/de/bede9bd80f3daf1d2d8e6d04166df5e3_259x168.png) ```cpp string getLongestCommonStr(const string& s1, const string& s2) { if (s1.empty() || s2.empty()) return ""; int m = s1.size(); int n = s2.size(); vector<vector<int>> f(m, vector<int>(n, 0)); int x = 0; int y = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (s1[i] == s2[j]) { if (i > 0 && j > 0) { f[i][j] = f[i-1][j-1] + 1; } else { f[i][j] = 1; } if (f[i][j] > f[x][y]) { x = i; y = j; } } } } return s1.substr(x - f[x][y] + 1, f[x][y]); } ```