题解 | #最长公共子序列(二)#

最长公共子序列(二)

https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11

#include<string>
#include <vector>

using namespace std;

class Solution {


  public:
    /**
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    int max(int a, int b) {
        return a > b ? a : b;
    }
    string LCS(string s1, string s2) {
        // write code here
        int len1, len2;
        len1 = s1.size();
        len2 = s2.size();
        vector<int>w(len2 + 1, 0);
        vector<vector<int>>arr(len1 + 1, w);

        for (int i = 1; i <= s1.length(); i++) {
            for (int j = 1; j <= s2.length(); j++) {
                if (s1[i - 1] == s2[j - 1]) {
                    arr[i][j] = arr[i - 1][j - 1] + 1;
                } else {
                    arr[i][j] = max(arr[i][j - 1], arr[i - 1][j]);
                }
            }
        }
        int k = 0;
        int i = len1, j = len2;
        string str;

        //for (; (i > 0) && (j > 0);)
        //{
        //    if (s1[i-1] == s2[j-1])
        //    {
        //        str[k++] = s1[i-1];
        //        i--; j--;
        //    }
        //    else
        //    {
        //        if (arr[i][j] == arr[i - 1][j])
        //        {
        //            i--;
        //        }
        //        else
        //        {
        //            j--;
        //        }
        //    }
        //}
        while (i > 0 && j > 0) {
            if (s1[i - 1] == s2[j - 1]) {
                str = str + s1[i - 1];
                //str.append(1, s1[i - 1]);
                i--;
                j--;
            } else {
                if (arr[i][j] == arr[i - 1][j]) {
                    i--;
                } else {
                    j--;
                }
            }
        }
        if(str.empty()) return "-1";
        reverse(str.begin(), str.end());
        return str;
    }
};

天啊终于!!对于string的赋值不能像C一样,需要用string自己的加法、或者追加!

全部评论

相关推荐

站队站对牛:兄弟 你这是四年就当大一过了吧 也许你校园卡 赚了有五位数了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务