Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
Solution:
dppos[i]==true/false表示字符串从开头到i的子串是否存在cut方案满足条件
动态规划设置初值bpos[0]==true
string.substr(int beginIndex, int length): 取string从beginIndex开始长length的子串
1 class Solution { 2 public: 3 bool wordBreak(string s, unordered_set<string>& wordDict) { //runtime:4ms 4 vector<bool> dppos(s.size()+1, false); 5 dppos[0]=true; 6 7 for(int i=1;i<dppos.size();i++){ 8 for(int j=i-1;j>=0;j--){ //从右到左找快很多 9 10 if(dppos[j]==true && wordDict.find(s.substr(j,i-j))!=wordDict.end()){ 11 dppos[i]=true; 12 break; //只要找到一种切分方式就说明长度为i的单词可以成功切分,因此可以跳出内层循环 13 } 14 } 15 } 16 return dppos[s.size()]; 17 } 18 };