Leetcode

[Leetcode] 97. Interleaving String

mjk- 2025. 3. 17. 19:32

문제

 

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 = s1 + s2 + ... + sn
  • t = t1 + t2 + ... + tm
  • |n - m| <= 1
  • The interleaving is 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:

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.

 

Follow up: Could you solve it using only O(s2.length) additional memory space?

 

풀이

 

2d dp array 를 사용하는게 키포인트다. 

(만약 output이 이전 element in array에 영향을 받고 boolean이면 거의 dynamic programming을 쓰는것 같다.)

왜 2D를 사용하는가? s3 가 2개의 array의 영향을 받기 때문이다. 

s3는 s1나 s2의 알파벳과 같고 && 그 전의 s1나 s2의 알파벳이 포함되어 있어야 한다. 

표로 생각하면 좀 더 이해하기 쉬운데, s1(위) 나 s2(왼쪽)이 true(알파벳 매칭)이여야 해당 셀도 참이 된다.

j \ i 0 1 2 3
0 true      
1        
2        
3       output

 

2d dp array를 사용함으로서, 일일이 비교해서 답을 찾을 때의 s1, s2의 비교 순서에 대한 어려움을 없앨 수 있다. 

 

코드

bool isInterleave(char* s1, char* s2, char* s3) {
    int size1 = strlen(s1);
    int size2 = strlen(s2);
    int size3 = strlen(s3);
    
    if(size1+size2 != size3) return false;
    
    int dp[size1+1][size2+1];
    memset(dp, false, sizeof(dp));
    
    dp[0][0] = true;
    
    for(int i=0; i<=size1; i++) {
        for(int j=0 ; j<=size2; j++) {
            int k = i + j - 1;
            if(i>0 && dp[i-1][j] && s1[i-1] == s3[k]) dp[i][j] = true;
            if(j>0 && dp[i][j-1] && s2[j-1] == s3[k]) dp[i][j] = true;
        }
    }
    
    return dp[size1][size2];
}