• 97. Interleaving String


    Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

    Example 1:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
    Output: true
    

    Example 2:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
    Output: false

    Approach #1: DP. [C++]

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            //if (s1 == "" && s2 == "" && s3 == "") return true;
            //if (s1 == "" || s2 == "" || s3 == "") return false;
            if (s1.length() + s2.length() != s3.length()) return false;
            
            vector<vector<bool>> match(s1.length()+1, vector<bool>(s2.length()+1, false));
            match[0][0] = true;
            
            for (int idx = 0; idx < s1.length() + s2.length(); ++idx) {
                for (int s1Len = 0; s1Len <= idx+1 && s1Len <= s1.length(); ++s1Len) {
                    int s2Len = idx + 1 - s1Len;
                    if (s2Len > s2.length()) continue;
                    if ((s1Len > 0 && match[s1Len-1][s2Len] && s3[idx] == s1[s1Len-1]) ||
                        (s2Len > 0 && match[s1Len][s2Len-1] && s3[idx] == s2[s2Len-1]))
                        match[s1Len][s2Len] = true;
                }
            }
            
            return match[s1.length()][s2.length()];
        }
    };
    

      

    Analysis:

    status: match[s1Len][s2Len] represent s1Len characters in s1 and s2Len characters in s2 wether match with s1Len+s2Len characters in s3.

    init: match[0][0] = true;

    func: 

    result: match[s1.length()][s2.length()].

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    javascript学习
    python学习计划
    利用spring的测试组建,测试bean
    log4j 输出完整的Exception信息
    根据身份证号,取得行政区划的Javascript实现
    软件全程建模1
    软件界面建模浅析
    RUP简介
    用例建模中的一个问题的讨论
    软件全程建模2
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10363367.html
Copyright © 2020-2023  润新知