zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Interleaving String **@

    https://oj.leetcode.com/problems/interleaving-string/

    刚开始用递归做,但是超时了

    class Solution {
    public:
        bool flag;
        
        bool isInterleave(string s1, string s2, string s3) {
            flag = false;
            if(s1.size() + s2.size() != s3.size())
                return flag;
                
            subIsInterleave(s1,s2,s3,0,0,0);
            return flag;
        }
        
        void subIsInterleave(string &s1, string &s2, string &s3, int p1, int p2, int p3)
        {
            if(p1 == s1.size() && p2 == s2.size() && p3 == s3.size())
            {
                flag = true;
                return;
            }
            if(!(p1 <= s1.size() && p2 <= s2.size() && p3 < s3.size()))
                return;
                
            if(s3[p3] != s1[p1] && s3[p3] != s2[p2])
            {
                return;
            }
            if(p1 < s1.size() && s3[p3] == s1[p1] && flag == false)
                subIsInterleave(s1,s2,s3,p1 + 1, p2,p3 + 1);
            if(p2 < s2.size() && s3[p3] == s2[p2] && flag == false)
                subIsInterleave(s1,s2,s3,p1,p2+1,p3 + 1);
        }
    };

    按照二维动态规划的思路,用两层for循环做

    记 flag[i][j] 为 s1[0,i] s2[0,j] 匹配 s3[0,i+j] 则:

    flag[i][j] = s1[i-1] == s3[i+j-1] && flag[i-1][j]  || s2[j-1] == s3[i+j-1] && flag[i][j-1];

    代码如下:

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            if(s3.size() != s1.size() + s2.size())
                return false;
            
            vector<vector<bool> > flag(s1.size()+1, vector<bool>(s2.size()+1, true));
            
            // init
            for(int i = 1; i < s1.size() + 1; i++)
                flag[i][0] = flag[i-1][0] && (s1[i-1] == s3[i-1]);
            for(int j = 1; j < s2.size() + 1; j++)
                flag[0][j] = flag[0][j-1] && (s2[j-1] == s3[j-1]);
            
            for(int i = 1; i < s1.size() + 1; i++)
                for(int j = 1; j < s2.size() + 1; j++)
                {
                    flag[i][j] = ((s1[i-1] == s3[i+j-1]) && flag[i-1][j]) || ((s2[j-1] == s3[i+j-1]) && flag[i][j-1]);
                }
            return flag[s1.size()][s2.size()];
        }
    };
  • 相关阅读:
    L309 单音节词读音规则(一)-辅音字母发音规则
    L308 New brain cells made throughout life
    L306 词汇题
    L305 发邮件15分钟
    L304 What Is Death?
    2019.3.22 Week 11 : ZigBee power test and field test
    L302 如何避免秃头
    2019.3.22 Week 12 : ZigBee and T/H chamber test
    L300 3月英语课下
    Pycharm使用方法之调整代码字体大小
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3911623.html
Copyright © 2011-2022 走看看