파비의 매일매일 공부기록

2023.08.04 Today's Challenge 본문

Problem Solving/LeetCode

2023.08.04 Today's Challenge

fabichoi 2023. 8. 4. 23:45

https://leetcode.com/problems/word-break/

 

Word Break - LeetCode

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

leetcode.com

BFS를 활용한 풀이

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        words = set(wordDict)
        queue = deque([0])
        seen = set()

        while queue:
            start = queue.popleft()
            if start == len(s):
                return True

            for end in range(start+1, len(s) + 1):
                if end in seen:
                    continue
                if s[start:end] in words:
                    queue.append(end)
                    seen.add(end)
        
        return False
반응형

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

2023.08.06 Today's Challenge  (0) 2023.08.06
2023.08.05 Today's Challenge  (0) 2023.08.05
2023.08.03 Today's Challenge  (0) 2023.08.03
2023.08.02 Today's Challenge  (0) 2023.08.02
2023.08.01 Today's Challenge  (0) 2023.08.01
Comments