1. 程式人生 > >【LeetCode】125.Interleaving String

【LeetCode】125.Interleaving String

題目描述(Hard)

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

題目連結

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

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

演算法分析

設狀態f[i][j]表示s1[i]和s2[j]匹配s3[i+j]。如果s1的最後一個字元等於s3的最後一個字元,則f[i][j]=f[i-1][j];如果s2的最後一個字元等於s3的最後一個字元,則f[i][j]=f[i][j-1]。因此狀態轉移方程如下:

f[i][j] = (s1[i - 1] == s3 [i + j - 1] && f[i - 1][j]) || (s2[j - 1] == s3 [i + j - 1] && f[i][j - 1]);

提交程式碼:

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