Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
Runtime: 6ms
1 class Solution { 2 public: 3 bool wordBreak(string s, unordered_set<string>& wordDict) { 4 if (s.empty()) return true; 5 6 // Have dp[i] indicate whether s[0...i-1] could be broken. 7 // If there is a dp[j] where j from [0, i - 1] is true, 8 // and s[j...i - 1] is in the dictionary, then dp[i] is true 9 vector<bool> dp(s.size() + 1, false); 10 dp[0] = true; 11 for (int i = 1; i <= s.size(); i++) { 12 for (int j = i; j >= 0; j--) { 13 if (dp[j] && wordDict.count(s.substr(j, i - j)) > 0) { 14 dp[i] = true; 15 break; 16 } 17 } 18 } 19 return dp[s.size()]; 20 } 21 };