<139> Word Break
Description
Question: Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note: The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Leetcode link: 139. Word Break
Quick Sum-up:
- Input: a string and an array of words
- Output: a boolean value indicating whether the string can be assembled by the words
- The string is non-empty.
- The array is non-empty.
Idea
- Compare the string with words in the dictionary. If a word appears in the string, slice the string and put the substring to the next round of matching until the string is empty. => TLE, fail on the 4th case
- Use BFS, the queue of BFS stores the start index of next round. In addition, we need to record whether an index has been stored in the queue. => Pass, 68ms
Test cases
Input | Output |
---|---|
s="leetcode" wordDict=["leet", "code"] |
true |
s="applepenapple" wordDict=["apple", "pen"] |
true |
s="catsandog" wordDict=["cats", "dog", "sand", "and", "cat"] |
false |
s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaab" wordDict=["a","aa","aaa","aaaa","aaaaa", "aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa", "aaaaaaaaaa"] |
false |
Solution
1 | /** |