image.png

    1. #include<iostream>
    2. #include<cstdio>
    3. #include<algorithm>
    4. #include<vector>
    5. using namespace std;
    6. int main(){
    7. string a, b;
    8. getline(cin, a);
    9. getline(cin, b);
    10. int n = a.size(), m = b.size();
    11. vector<vector<int>>dp(n+1, vector<int>(m+1, 0));
    12. int max_end = 0;
    13. int max_v = 0;
    14. for(int i = 1; i <= n; i++){
    15. for(int j = 1; j <= m; j++){
    16. if(a[i-1] == b[j-1]){
    17. dp[i][j] = dp[i-1][j-1] + 1;
    18. }else{
    19. dp[i][j] = 0;
    20. }
    21. if(dp[i][j] > max_v){
    22. max_v = dp[i][j];
    23. max_end = j-1;
    24. }
    25. }
    26. }
    27. if(max_v == 0){
    28. puts("-1");
    29. }else{
    30. string res = "";
    31. for(int k = 0; k < max_v; k++){
    32. res += b[max_end-k];
    33. }
    34. reverse(res.begin(), res.end());
    35. cout<<res<<endl;
    36. }
    37. return 0;
    38. }

    image.png

    如果要记录最长子串的长度,那么知道了最大的长度,只需要记录末尾的下标就行
    所以只需要在更新最大长度的时候,记录子串的末尾的下标,再根据最大长度倒推出最大子串。