본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 97. Interleaving String

반응형

Interleaving String

Difficulty: Medium


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?

 

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n, m = len(s1), len(s2)

        if n + m != len(s3) :
            return False

        dp = [[False for _ in range(m+1)] for _ in range(n+1)]
        dp[0][0] = True

        for i in range(n+1) :
            for j in range(m+1) :
                if i >= 1 and dp[i-1][j] and s1[i-1] == s3[i+j-1] :
                    dp[i][j] = True
                if j >= 1 and dp[i][j-1] and s2[j-1] == s3[i+j-1] :
                    dp[i][j] = True

        return dp[n][m]

이렇게 직접 그려보면 나올것이다. 조건에 대해 다시 한 번 생각해보자. (사실 나도 잘 모르겠다. 스터디에서 물어봐야지) 

  1. 패딩을 했기 때문에 i, j는 1 이상에서 시작해야 한다.
  2. DP 테이블을 기준으로 직전에 True 라면 (그림에서는 1) 현재 들어온 글씨에 대해 판단을 할 수 있을것이다. 
  3. 현재 글자가 조합된 글자의 순서와 동일하다면, dp[current_i][current_j] = True 처리 한다. 

이 조건을 잘 생각해보면 DP 테이블을 False와 True로 채워나갈 수 있을 것이다. 

반응형