【LeetCode】139 - Word Break

时间:2023-03-08 20:42:10

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的子串

 class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {    //runtime:4ms
vector<bool> dppos(s.size()+, false);
dppos[]=true; for(int i=;i<dppos.size();i++){
for(int j=i-;j>=;j--){  //从右到左找快很多 if(dppos[j]==true && wordDict.find(s.substr(j,i-j))!=wordDict.end()){  
dppos[i]=true;
break;   //只要找到一种切分方式就说明长度为i的单词可以成功切分,因此可以跳出内层循环
}
}
}
return dppos[s.size()];
}
};