2020年5月23日
LeetCode 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.
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: true Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"] Output: true 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: false
解析:给定一个非空的字符串和包含非空字符串的词典,判断字符串通过不同方式的切割,能够完全匹配词典中的词语。
采用动态规划进行求解,假设dp[i]表示以i结尾的字符串能否分割成词典中的词语。字符长度len=s.size(),则dp数组长度为len+1。外层循环控制每个下标i,内层循环控制j<i。假设dp[j]已经计算好,则判断从i到j的片段是否出现在词典中。如果出现了,并且dp[j]=true,则此时dp[i]=true。具体代码如下:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.size();
vector<bool> dp(len+1, false);
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
dp[0] = true;
for(int i=0; i <=len; i++)
{
for(int j=0; j < i; j++)
{
string temp = s.substr(j, i-j);
if(dp[j] && wordSet.find(temp) != wordSet.end())
{
dp[i] = true;
break;
}
}
}
return dp[len];
}
};
One Comment