139.Word Break 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. You may assume the dictionary does not contain duplicate words.
For example, given s = "leetcode", dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
比如这题,可以用一个数组dp记录S[0:i]是否能break。
dp[i]:S[0:i-1]是否能被break。例如dp[1]表示s[0]是否能被break。 dp[0] = true dp[i] = true if and only if:
- 存在一个i-1>=k>=0,使s[k:i-1]存在于dict中。
- s[0: k-1]可以被break,即dp[k] = true。
class Solution { public: bool wordBreak(string s, unordered_set<string> &dict) { vector<bool> dp(s.size()+1,false); dp[0] = true; for(int i=0; i<s.size(); i++) { for(int j=i; j>=0; j--) { if(dp[j] && dict.count(s.substr(j,i-j+1))!=0) { dp[i+1] = true; break; } } } return dp[s.size()]; } };
REF: