zoukankan      html  css  js  c++  java
  • 97. Interleaving String *HARD* -- 判断s3是否为s1和s2交叉得到的字符串

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

    For example,
    Given:
    s1 = "aabcc",
    s2 = "dbbca",

    When s3 = "aadbbcbcac", return true.
    When s3 = "aadbbbaccc", return false.

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            int l1 = s1.size(), l2 = s2.size(), i, j;
            if(l1 + l2 != s3.size())
                return false;
            vector<vector<bool>> isMatch(l1+1, vector<bool>(l2+1, false));
            isMatch[0][0] = true;
            for(i = 1; i <= l1; i++)
            {
                if(s1[i-1] == s3[i-1])
                    isMatch[i][0] = true;
                else
                    break;
            }
            for(i = 1; i <= l2; i++)
            {
                if(s2[i-1] == s3[i-1])
                    isMatch[0][i] = true;
                else
                    break;
            }
            for(i = 1; i <= l1; i++)
            {
                for(j = 1; j <= l2; j++)
                {
                    isMatch[i][j] = ((s1[i-1] == s3[i+j-1]) && isMatch[i-1][j]) || ((s2[j-1] == s3[i+j-1]) && isMatch[i][j-1]);
                }
            }
            return isMatch[l1][l2];
        }
    };

    Considering:

    s1 = a1, a2 ........a(i-1), ai
    s2 = b1, b2, .......b(j-1), bj
    s3 = c1, c3, .......c(i+j-1), c(i+j)


    Defined

    match[i][j] means s1[0..i] and s2[0..j] is matched S3[0..i+j]

    So, if ai == c(i+j), then match[i][j] = match[i-1][j], which means

    s1 = a1, a2 ........a(i-1)
    s2 = b1, b2, .......b(j-1), bj
    s3 = c1, c3, .......c(i+j-1)

    Same, if bj = c(i+j), then match[i][j] = match[i][j-1];

    Formula:

    Match[i][j] =
    (s3[i+j-1] == s1[i]) && match[i-1][j] ||
    (s3[i+j-1] == s2[j]) && match[i][j-1]

    Initialization:

    i=0 && j=0, match[0][0] = true;

    i=0, s3[j] == s2[j], match[0][j] |= match[0][j-1]
    s3[j] != s2[j], match[0][j] = false;

    j=0, s3[i] == s1[i], match[i][0] |= match[i-1][0]
    s3[i] != s1[i], Match[i][0] = false;

  • 相关阅读:
    练习!!标准体重
    C# 阶乘累加
    C# 阶乘
    C# 累加求和
    C# 100块钱,买2元一只的圆珠笔3块钱一个的尺子5元一个的铅笔盒每样至少一个,正好花光,有多少种花法。
    C# 一张纸0.00007m,折多少次和珠峰一样高
    C# 100以内质数
    C# 100以内质数和
    网站的基本布局
    C#递归
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5410835.html
Copyright © 2011-2022 走看看