파비의 매일매일 공부기록

2023.08.25 Today's Challenge 본문

Problem Solving/LeetCode

2023.08.25 Today's Challenge

fabichoi 2023. 8. 25. 23:45

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

 

Interleaving String - LeetCode

Can you solve this real interview question? 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 subs

leetcode.com

DP로 푸는 문제

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        m, n, l = len(s1), len(s2), len(s3)
        if m + n != l:
            return False
        if m < n:
            return self.isInterleave(s2, s1, s3)
        
        dp = [False] * (n+1)
        dp[0] = True

        for j in range(1, n+1):
            dp[j] = dp[j-1] and s2[j-1] == s3[j-1]
        
        for i in range(1, m+1):
            dp[0] = dp[0] and s1[i-1] == s3[i-1]
            for j in range(1, n+1):
                dp[j] = (dp[j] and s1[i-1] == s3[i+j-1]) or (dp[j-1] and s2[j-1] == s3[i+j-1])
        
        return dp[n]
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.08.27 Today's Challenge  (0) 2023.08.27
2023.08.26 Today's Challenge  (0) 2023.08.26
2023.08.24 Today's Challenge  (0) 2023.08.24
2023.08.23 Today's Challenge  (0) 2023.08.23
2023.08.22 Today's Challenge  (0) 2023.08.22
Comments