Problem
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.
Example1
Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.
Example2
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.
Example3
Input: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
Output: false
Solution
動態規劃
狀態表示
轉移方程
用指針 j去劃分兩部分
[0, i] 區間子串 的 dp[i+1] 爲真,取決於兩部分:
它的前綴子串 [0, j-1] 的 dp[j] 爲真
剩餘子串 [j,i] 是一個合格的單詞
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
if(n == 0)
return true;
vector<bool> dp(n+1,false);
unordered_set<string> wordDictSet(wordDict.begin(),wordDict.end());
dp[0] = true;
for(int i =1;i<=n;i++)
{
if(dp[i-1])
{
int indx = i-1;
for(int j = indx;j<n;j++)
{
string cur = s.substr(indx,j-indx+1);
if(wordDictSet.find(cur) != wordDictSet.end())
dp[j+1] = true;
}
}
}
return dp[n];
}
};
Ref
https://leetcode-cn.com/problems/word-break/solution/shou-hui-tu-jie-san-chong-fang-fa-dfs-bfs-dong-tai/