zoukankan      html  css  js  c++  java
  • 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.

    这道题最初想用贪心,实际策略就错了

    后面看了dp的做法。

    就是根据当前状态,i表示查看S1的位置,j表示查看S2的位置,i+j表示到S3的位置。

    需要判断如果当前状态可由两个串的前部分组成,再加入一个字符时候可以依然由两个字符串的前部分组成。

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            int l1 =s1.size(),l2=s2.size(),l3=s3.size();
            if(l1+l2 != l3)return 0;
            vector<vector<bool> > dp;
            for(int i = 0 ; i < l2+1 ;i++)
            {
                vector<bool> bo(l1+1,0);
                dp.push_back(bo);
            }
            dp[0][0] = 1;
            for(int i = 0 ; i <l2+1 ;i++)
            {
                for(int j = 0 ; j < l1+1 ;j++)
                {
                    if(dp[i][j] && i+j < l3)
                    {
                        if(j<l1 && s3[i+j] == s1[j]) dp[i][j+1] = 1;
                        
                        if(i<l2 && s3[i+j] == s2[i]) dp[i+1][j] = 1;
                    }
                }
            }
            
            return dp[l2][l1];
    
        }
        
    };
    

      

  • 相关阅读:
    734. Sentence Similarity
    Rainbow Sort
    692. Top K Frequent Words
    347. Top K Frequent Elements
    12. Integer to Roman
    13. Roman to Integer
    109. Convert Sorted List to Binary Search Tree
    用表单写兴趣爱好的程序
    方法重载与方法重写的区别
    super和this的区别
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3674786.html
Copyright © 2011-2022 走看看