• 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.

    Recurse:
    Judge Small: Accepted! 
    Judge Large: Time Limit Exceeded

     1 bool isInterleave(string s1, string s2, string s3) {  
     2         // Start typing your C/C++ solution below  
     3         // DO NOT write int main() function      
     4         if(s1.length() == 0) return s3 == s2;  
     5         if(s2.length() == 0) return s3 == s1;  
     6         if(s3.length() == 0) return s1.length() + s2.length() == 0;  
     7           
     8         if(s1[0] == s3[0] && s2[0] != s3[0])  
     9             return isInterleave(s1.substr(1), s2, s3.substr(1));  
    10         else if(s1[0] != s3[0] && s2[0] == s3[0])  
    11             return isInterleave(s1, s2.substr(1), s3.substr(1));  
    12         else if(s1[0] == s3[0] && s1[0] == s3[0])  
    13             return isInterleave(s1.substr(1), s2, s3.substr(1)) || isInterleave(s1, s2.substr(1), s3.substr(1));  
    14         else  
    15             return false;  
    16     }  

    2-dimension dp:

    这是一个二维的动态规划,

    s1 = "aabcc"
    s2 = "dbbca"
    s3 = "aadbbcbcac"

     1 class Solution {
     2 public:
     3     bool isInterleave(string s1, string s2, string s3) {
     4         if(s3.length()!=s1.length()+s2.length()) return false;
     5         vector<vector<bool>> res(s1.length()+1,vector<bool>(s2.length()+1, false));
     6         res[0][0]=true;
     7         for(int i=1;i<=s1.length();i++){
     8             res[i][0]=res[i-1][0]&&s1[i-1]==s3[i-1];
     9         }
    10         for(int j=1;j<=s2.length();j++){
    11             res[0][j]=res[0][j-1]&&s2[j-1]==s3[j-1];
    12         }
    13         for(int i=1;i<=s1.length();i++){
    14             for(int j=1;j<=s2.length();j++){
    15                 res[i][j]=(res[i-1][j]&&s1[i-1]==s3[i+j-1])||(res[i][j-1]&&s2[j-1]==s3[i+j-1]);
    16             }
    17         }
    18         return res[s1.length()][s2.length()];
    19     }
    20     
    21 };
  • 相关阅读:
    C++下载数据至.map/.txt/.list文件
    Byte数组转浮点数
    linux下进程的最大线程数、进程最大数、进程打开的文件数
    linux后台程序开发常用工具
    linux下csv导出文件中文乱码问题
    50个高端大气上档次的管理后台界面模板(转)
    如何注册.net 的类库dll 为com组件(转)
    vue页面信息
    CSS特效
    Css样式
  • 原文地址:https://www.cnblogs.com/zl1991/p/7056057.html
Copyright © 2020-2023  润新知