LeetCode //C - 97. Interleaving String

97. Interleaving String

Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

An interleaving of two strings s and t is a configuration where s and t are divided into n and m
substrings
respectively, such that:

  • s = s 1 + s 2 + . . . + s n s = s_1 + s_2 + ... + s_n s=s1+s2+...+sn
  • t = t 1 + t 2 + . . . + t m t = t_1 + t_2 + ... + t_m t=t1+t2+...+tm
  • ∣ n − m ∣ < = 1 |n - m| <= 1 nm<=1
  • The interleaving is s 1 + t 1 + s 2 + t 2 + s 3 + t 3 + . . .   o r   t 1 + s 1 + t 2 + s 2 + t 3 + s 3 + . . . s_1 + t_1 + s_2 + t_2 + s_3 + t_3 + ...\ or \ t_1 + s_1 + t_2 + s_2 + t_3 + s_3 + ... s1+t1+s2+t2+s3+t3+... or t1+s1+t2+s2+t3+s3+...

Note: a + b is the concatenation of strings a and b.
 

Example 1:

LeetCode //C - 97. Interleaving String_第1张图片

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
Output: true
Explanation: One way to obtain s3 is:
Split s1 into s1 = “aa” + “bc” + “c”, and s2 into s2 = “dbbc” + “a”.
Interleaving the two splits, we get “aa” + “dbbc” + “bc” + “a” + “c” = “aadbbcbcac”.
Since s3 can be obtained by interleaving s1 and s2, we return true.

Example 2:

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
Output: false
Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.

Example 3:

Input: s1 = “”, s2 = “”, s3 = “”
Output: true

Constraints:
  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2, and s3 consist of lowercase English letters.

From: LeetCode
Link: 97. Interleaving String


Solution:

Ideas:
  • Check if sum of s1 and s2 lengths equals s3 length
  • Use DP to check if s3 can be formed by interleaving s1 and s2
  • DP state is dp[i][j] = true if s3[0…i+j-1] can be formed by interleaving s1[0…i-1] and s2[0…j-1]
Code:
bool isInterleave(char* s1, char* s2, char* s3) {
    int m = strlen(s1);
    int n = strlen(s2);
    int t = strlen(s3);
    
    if (m + n != t) {
        return false;
    }
    
    bool dp[m+1][n+1];
    memset(dp, false, sizeof(dp));
    dp[0][0] = true;
    
    for(int i=0; i<=m; i++) {
        for(int j=0; j<=n; j++) {
            if (i > 0 && s1[i-1] == s3[i+j-1] && dp[i-1][j]) {
                dp[i][j] = true; 
            }
            if (j > 0 && s2[j-1] == s3[i+j-1] && dp[i][j-1]) {
                dp[i][j] = true;
            }
        }
    }
    
    return dp[m][n];
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)