Word Break
Easy
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.
A dictionary word may be used multiple times.
The words must form the entire string without changing their order or characters.
Example 1
Input
n = 2 wordDict = ["leet", "code"] s = "leetcode"
Output
true
Explanation
The string can be segmented as:
"leet" + "code"
Both words are present in wordDict.
Example 2
Input
n = 5 wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] s = "pineapplepenapple"
Output
true
Explanation
One valid segmentation is:
"pine" + "apple" + "pen" + "apple"
All four words are present in the dictionary.
Constraints
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of lowercase English letters.
All strings in wordDict are unique.
Hints:
Hint 1
Let dp[i] represent whether the first i characters of s can be segmented using the dictionary.
Hint 2
For every position i, check whether there is a previous position j such that:
dp[j] = true
and:
s[j...i-1]
is a dictionary word.
Auto
Loading editor...
Input
Expected Output