본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 139. Word Break

반응형

Word Break

Difficulty: Medium


Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

 

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false

 

Constraints:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

 

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        n = len(s)
        dp = [False for _ in range(n + 1)]
        dp[0] = True
        wordSet = set(wordDict)

        for i in range(1, n + 1) :
            for j in range(i) :
                if dp[j] and s[j:i] in wordSet :
                    dp[i] = True
                    break
        
        return dp[-1]

다양한 방법으로 풀 수 있겠지만, DP로 해결하였다. 

이중 for 문에서 i는 문자의 끝, j는 문자의 시작을 의미하고 dp[j]가 True 일때만 유효하므로 j부터 i까지 문자가 wordDict에 있으면 문자열 끝인 dp[i]에 True 를 적는다. 다음 체크포인트가 되겠지?

다른 테스트 케이스로 "aaaaaaa" 을 wordDict = ["aaaa", "aaa"]인 케이스가 있었다. 처음에 3번째 a에 True가 체크될 것이고 이후 4번째 a에도 True가 체크될 것이다. 그리고 6번째와 마지막 a에 True가 체크 될 것이다. 

반응형