[leetcode] 139. Word Break
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
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.
Example 1:
Input:
s = "leetcode", wordDict = ["leet", "code"]
Output:
Explanation:
Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input:
s = "applepenapple", wordDict = ["apple", "pen"]
Output:
Explanation:
Return true because "applepenapple" can be segmented as "apple pen
apple". Note that you are allowed to reuse a dictionary word.
Example 3:
Input:
s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
分析
题目的意思是:判断一个字符串能否分割成若干个字典中的单词。
- dp[i] 表示源串的前i个字符可以满足分割,那么 dp[ j ] 满足分割的条件是存在k 使得 dp [k] && substr[k,j]在字典里。
代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.size()+1,false);
dp[0]=true;
for(int i=0;i<s.length();i++){
for(int j=i;j<s.length()&&dp[i];j++){
if(find(wordDict.begin(),wordDict.end(),s.substr(i,j-i+1))!=wordDict.end()){
dp[j+1]=true;
}
}
}
return dp[s.length()];
}
};
参考文献
[编程题]word-break[Leetcode] Word Break、Word BreakII