Word Break
ID:139
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.
Idea
Always start from the beginning of the string, check if there's a fit in wordDict for the starting substring.
If so, check for the later part of the string to check the starting substring in wordDict......
If the resulting substring after truncating the part that is equals to the dict word has a length=0, meaning all characters in the string found its corresponding dict word, then return true, since the entire string can be partitioned based on wordDict
Also, use a List or HashMap to keep track of already seen pattern. In corner cases like s = "aaaaaaaaaaaaab" and wordDict = ["a","aa","aaa","aaaaa"], we can save a lot of time when a previous pattern is already seen by returning false
Code
Last updated