139.Word Break
Word Break Total Accepted: 44934 Total Submissions: 198482 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 Have you met this question in a real interview? Yes No
思路:动态规划: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[n];
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;
}
};