【LeetCode】97. Interleaving String


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.

 

可以用遞歸做,每匹配s1或者s2中任意一個就遞歸下去。但是會超時。

因此考慮用動態規划做。

s1, s2只有兩個字符串,因此可以展平為一個二維地圖,判斷是否能從左上角走到右下角。

當s1到達第i個元素,s2到達第j個元素:

地圖上往右一步就是s2[j-1]匹配s3[i+j-1]。

地圖上往下一步就是s1[i-1]匹配s3[i+j-1]。

示例:s1="aa",s2="ab",s3="aaba"。標1的為可行。最終返回右下角。

     0  a  b

0   1  1  0

a   1  1  1

a   1  0  1

 

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int m = s1.size();
        int n = s2.size();
        if(m+n != s3.size())
            return false;
        vector<vector<bool> > path(m+1, vector<bool>(n+1, false));
        for(int i = 0; i < m+1; i ++)
        {
            for(int j = 0; j < n+1; j ++)
            {
                if(i == 0 && j == 0)
                // start
                    path[i][j] = true;
                else if(i == 0)
                    path[i][j] = path[i][j-1] & (s2[j-1]==s3[j-1]);
                else if(j == 0)
                    path[i][j] = path[i-1][j] & (s1[i-1]==s3[i-1]);
                else
                    path[i][j] = (path[i][j-1] & (s2[j-1]==s3[i+j-1])) || (path[i-1][j] & (s1[i-1]==s3[i+j-1]));
            }
        }
        return path[m][n];
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM