标签:on() return mes cin sub ++ str div std
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; //最长公共子串 class Solution { public: int longestSubstring(string x, string y) { if (x.size() > y.size()) swap(x, y); // 题目要求短串优先 vector<vector<int> > f(x.size() + 1, vector<int>(y.size() + 1)); int max = 0, pos = 0; for (int i = 1; i <= x.size(); i++) { for (int j = 1; j <= y.size(); j++) { if (x[i - 1] != y[j - 1]) f[i][j] = 0; else f[i][j] = f[i - 1][j - 1] + 1; if (max < f[i][j]) { // 细节:不能有等号 因为多个答案只取短串中最早出现的子串 max = f[i][j]; pos = i; } } } cout << x.substr(pos - max, max) << endl; return max; } }; int main() { string x, y; while (cin >> x >> y) { Solution().longestSubstring(x, y); } return 0; }
标签:on() return mes cin sub ++ str div std
原文地址:https://www.cnblogs.com/joker1937/p/10635356.html