• 97. Interleaving String


    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.

    public bool IsInterleave(string s1, string s2, string s3) {
            if(s1 == "") return s2 == s3;
            if(s2 == "") return s1 == s3;
            if(s1.Length + s2.Length != s3.Length) return false;
            return Dp(s1,s2,s3,0,0,0);
        }
        
        private bool Dp(string s1, string s2, string s3, int i1,int i2, int i3)
        {
            if(i3 == s3.Length) return true;
            else if(i1 >= s1.Length && i2 >= s2.Length) return false;
            else
            {
                bool judgeS1 = false;
                bool judgeS2 = false;
                if(i1 <s1.Length && s1[i1] == s3[i3])
                {
                   judgeS1 = Dp(s1,s2,s3,i1+1,i2,i3+1);
                }
                if(judgeS1) return true;
                if(i2 < s2.Length && s2[i2] == s3[i3])
                {
                    judgeS2 = Dp(s1,s2,s3,i1,i2+1,i3+1);
                }
                return  judgeS2;
            }
        }
    public bool IsInterleave(string s1, string s2, string s3) {
            if(s1 == "") return s2 == s3;
            if(s2 == "") return s1 == s3;
            if(s1.Length + s2.Length != s3.Length) return false;
            var dp = new bool[s1.Length+1,s2.Length+1];
            dp[0,0] = true;
            for(int i = 1;i<= s2.Length;i++)
            {
                dp[0,i] = dp[0,i-1] && (s2[i-1] == s3[i-1]); 
            }
            for(int i = 1;i<= s1.Length;i++)
            {
                for(int j = 0;j<= s2.Length;j++)
                {
                    if(j ==0) dp[i,j] = dp[i-1,j] && (s1[i-1] == s3[i-1]);
                    else
                    {
                        dp[i,j] = (dp[i-1,j]&&(s1[i-1] == s3[j+i-1]))|| (dp[i,j-1]&&(s2[j-1] == s3[j+i-1]));
                    }
                }
            }
            return dp[s1.Length,s2.Length];
        }
  • 相关阅读:
    [android 应用框架api篇] bluetooth
    [uiautomator篇] bluetooth---接口来做
    [uiautomator篇] 设置@test的执行顺序
    [automator学习篇]android 接口-- bluetooth
    SharePoint : 使用SPQuery对象时要注意的事项
    SharePoint 2013版本功能对比介绍
    SharePoint Srver 2010 资源汇总
    实现简单的WebPart
    GAC的理解及其作用
    Bat命令学习
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5891242.html
Copyright © 2020-2023  润新知