LeetCode刷题实战139:单词拆分
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.
题意
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
解题
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<int> dp(s.size()+1, 0);
dp[0] = 1;
unordered_set<string> st(wordDict.begin(), wordDict.end());
for(int i = 1; i <= s.size(); i++)
{
for(int j = 0; j < i; j++)
{
auto pos = st.find(s.substr(j, i-j));
if(dp[j] && pos != st.end())
{
dp[i] = 1;
break;
}
}
}
return dp[s.size()];
}
};