파비의 매일매일 공부기록

2023.04.16 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.16 Today's Challenge

fabichoi 2023. 4. 16. 23:45

https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/

 

Number of Ways to Form a Target String Given a Dictionary - LeetCode

Can you solve this real interview question? Number of Ways to Form a Target String Given a Dictionary - You are given a list of strings of the same length words and a string target. Your task is to form target using the given words under the following rule

leetcode.com

class Solution:
    def numWays(self, words: List[str], target: str) -> int:
        ab = 26
        mod = 1000000007
        m, k = len(target), len(words[0])
        cnt = [[0] * k for _ in range(ab)]

        for j in range(k):
            for word in words:
                cnt[ord(word[j]) - ord('a')][j] += 1
        
        dp = [[0] * (k+1) for _ in range(m+1)]
        dp[0][0] = 1

        for i in range(m+1):
            for j in range(k):
                if i < m:
                    dp[i+1][j+1] += (cnt[ord(target[i]) - ord('a')][j] * dp[i][j])
                    dp[i+1][j+1] %= mod
                
                dp[i][j+1] += dp[i][j]
                dp[i][j+1] %= mod
        
        return dp[m][k]
반응형

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

2023.04.18 Today's Challenge  (0) 2023.04.18
2023.04.17 Today's Challenge  (0) 2023.04.17
2023.04.15 Today's Challenge  (0) 2023.04.15
2023.04.14 Today's Challenge  (0) 2023.04.14
2023.04.13 Today's Challenge  (0) 2023.04.13
Comments