Interleaving String
Problem
Given strings , , and , find whether is formed by an interleaving of and .
An interleaving of two strings and is a configuration where and are divided into and substrings respectively, such that:
- The interleaving is either
Note: is the concatenation of strings and
Example
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.
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.
Input: s1 = "", s2 = "", s3 = ""
Output: true
Constraints
Submit your solution at here
Solution
Approach
- We use an array , where denotes if we can use and to form a valid string
- By that definition, we have, , use 0 char from s1, 0 char from s2, we can form an empty string
- Calculate , we have 2 posibility
- If we use to form ,
- If we use to form ,
Complexity
- Time complexity:
- Space complexity: , with a little optimization, we can have
Code
space
impl Solution {
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let s1 = s1.as_bytes();
let s2 = s2.as_bytes();
let s3 = s3.as_bytes();
let n = s1.len();
let m = s2.len();
let nm = s3.len();
if n+m != nm {
return false;
}
let mut f = vec![vec![false;m+1];n+1];
for i in 0..=n {
for j in 0..=m {
f[i][j] = (i == 0 && j == 0) ||
(i > 0 && f[i-1][j] && s1[i-1] == s3[i+j-1]) ||
(j > 0 && f[i][j-1] && s2[j-1] == s3[i+j-1]);
}
}
return f[n][m];
}
}
space
impl Solution {
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let s1 = s1.as_bytes();
let s2 = s2.as_bytes();
let s3 = s3.as_bytes();
let n = s1.len();
let m = s2.len();
let nm = s3.len();
if n+m != nm {
return false;
}
let mut f = vec![false;m+1];
for i in 0..=n {
for j in 0..=m {
f[j] = (i == 0 && j == 0) ||
(i > 0 && f[j] && s1[i-1] == s3[i+j-1]) ||
(j > 0 && f[j-1] && s2[j-1] == s3[i+j-1]);
}
}
return f[m];
}
}