【LeetCode Contest 141】

Leetcode first week tournament, 10:45 think of it.
Game link: https://leetcode.com/contest/weekly-contest-141/

The former two are logical question is relatively simple, but read the question too slow, with C ++ syntax are not familiar with, always wrong.
The third channel 1091 bfs, directly recording the number of steps, position of the current neighbor is not accessed or updated number of steps, queued. No bfs any skills. Read or does not understand the question, delayed for a long time.

The fourth way is hard difficult questions. Look explanations written.

Topic links: 1092. Shortest the Common Supersequence

To two strings str1, str2, seeking a string s, str1 and str2 are sequences of s, s requires a minimum length.

Ideas:

First find the LCS, and then traverse the two strings, if the current character in the LCS, the join ans, adding that otherwise are not LCS characters. I.e. remaining characters inserted in the LCS.

Code:

class Solution {
public:
    string shortestCommonSupersequence(string str1, string str2) {
        int l1 = str1.length();
        int l2 = str2.length();
        vector<vector<int> > dp(l1+1, vector<int>(l2+1, 0));
        dp[0][0] = (str1[0] == str2[0] ? 1 : 0);
     
        for (int i=1; i<=l1; ++i) {
            for (int j=1; j<=l2; ++j) {
                if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
                else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
        
        string ans = "";
        while(l1 || l2) {
            char temp;
            if (l1 <= 0) temp = str2[--l2];
            else if (l2 <= 0) temp = str1[--l1];
            else if (str1[l1-1] == str2[l2-1]) temp = str1[--l1] = str2[--l2];
            else temp = (dp[l1][l2] == dp[l1-1][l2] ? str1[--l1] : str2[--l2]);
            ans += temp;
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

This question is still feeling confusedly.
This week in and week season to continue.

Last night and stay up late to see the drama. . . . massacre.
You can not really test their self-control. Away from temptation.
This week or continue to see faster rcnn source it ... do not know what to do all day. . . .

Guess you like

Origin blog.csdn.net/iCode_girl/article/details/92586006