• 97. Interleaving String (String; DP)


    Given s1, s2, s3, 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) {
            //dp[i][j]: s3[i+j-1] can be interleaved by s1[0..i], s2[0..j]
            //dp[i][j] = dp[i-1][j] if s3[i+j-1]==s1[i]
            //            = dp[i][j-1] if s3[i+j-1]==s2[j]
            //so traverse i,j,k from small to large
            int len1 = s1.length();
            int len2 = s2.length();
            if(len1+len2!=s3.length()) return false;
            vector<vector<bool>> dp(len1+1, vector<bool>(len2+1, false));
            
            //initial status
            dp[0][0] = true; //0 means null string
            for(int j = 1; j <= len2; j++){
                dp[0][j] = dp[0][j-1] && s2[j-1]==s3[j-1];
            }
            for(int i = 1; i <= len1; i++){
                dp[i][0] = dp[i-1][0] && s1[i-1]==s3[i-1];
            }
            
            //state transfer
            for(int i = 1; i<= len1; i++){
                for(int j = 1; j <= len2; j++){
                    dp[i][j] = (dp[i][j-1] && s2[j-1]==s3[i+j-1]) || (dp[i-1][j] && s1[i-1]==s3[i+j-1]);
                }
            }
            return dp[len1][len2];
        }
    };
  • 相关阅读:
    点赞
    js点击事件,数字累加
    html中hr的各种样式使用
    基于Bootstrap垂直响应的jQuery时间轴特效
    bootstrop日历
    前端经验
    bootstrop登陆页面
    bootstrop设置背景图片自适应屏幕
    建立博客的第一天
    php伪静态--隐藏地址实际路径方法
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4919275.html
Copyright © 2020-2023  润新知