您的位置:首页 > 其它

【LeetCode】139 - Word Break

2015-08-11 23:38 453 查看
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()+1, false);
dppos[0]=true;

for(int i=1;i<dppos.size();i++){
for(int j=i-1;j>=0;j--){  //从右到左找快很多

if(dppos[j]==true && wordDict.find(s.substr(j,i-j))!=wordDict.end()){  
dppos[i]=true;
break;   //只要找到一种切分方式就说明长度为i的单词可以成功切分,因此可以跳出内层循环
}
}
}
return dppos[s.size()];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: