问题描述:
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来解。
对与s的每个位置,可以尝试向前匹配wordDict里面的每个单词。
即
int len = (int)w.size();
if(i - len > -1 && dp[i-len]){
if(s.substr(i-len, len) == w){
dp[i] = true;
break;
}
}
这里先检查了dp[i-len]是否能够匹配成功。
若能够,则检查这个长度的子串是否存在dict中
代码:
class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int minLen = INT_MAX; int n = s.size(); vector<bool> dp(n+1, false); dp[0] = true; for(int i = 0; i <= n; i++){ for(auto w : wordDict){ int len = (int)w.size(); if(i - len > -1 && dp[i-len]){ if(s.substr(i-len, len) == w){ dp[i] = true; break; } } } } return dp[n]; } };