139.Word Break
2015-04-08 00:02
134 查看
Word Break
Total Accepted: 44934 TotalSubmissions: 198482My Submissions
Question
Solution
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".
Show Tags
Dynamic Programming
Have you met this question in a real interview?
Yes
No
Discuss
思路:动态规划:1.dp[i]表示s[0....i]能否由dict组成;2.递推关系是 如果dp[i]可以,则遍历dict中的单词,如果该单词在以s[i+1]开始的位置,则dp[i+单词长度]也可以
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int n=s.size();
if(n==0) return false;//判错
//初始化
bool *dp=new bool
;
for(int i=0;i<n;++i){
dp[i]=false;
}
for(auto i:dict){
if(s.find(i)==0){
dp[i.size()-1]=true;
}
}
//dp过程
int pos=0;
while(pos<n){
if(dp[pos]){
++pos;
for(auto i:dict){
if(s.find(i,pos)==pos){
dp[pos+i.size()-1]=true;
}
}
}else{
++pos;
}
}
//输出
bool res=dp[n-1];
delete []dp;
return res;
}
};
相关文章推荐
- leetcode-139-Word Break
- leetcode 139. Word Break
- 139. Word Break
- (M)Dynamic Programming:139. Word Break
- 139. Word Break
- LeetCode(139)Word Break
- Leetcode#139 Word Break
- 【LeetCode】139 - Word Break
- [leetcode] 139 Word Break
- LeetCode 139. Word Break
- 139. Word Break(dp)
- 139. Word Break
- 139. Word Break
- [Leetcode] #139 Word Break
- 139. Word Break
- leetcode 139 —— Word Break
- leetcode 139. Word Break
- LeetCode 139. Word Break(单词分隔)
- leetcode 139. Word Break(dp,字典匹配)
- 139. Word Break