题目描述
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"].
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".
IDEA
字符串被字典分割。动态规划法,用dp[i]=true表示s[0,..,i]的子字符串是能被分割
s.strsub(j,i-j)表示取s中从j到i(不包括i)的子串
CODE
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int len=s.length();
vector<bool> dp(len+1,false);
dp[0]=true;
for(int i=1;i<=len;i++){
for(int j=i-1;j>=0;j--){
if(dict.find(s.substr(j,i-j))!=dict.end()&&dp[j]){
dp[i]=true;
}
}
}
return dp[len];
}
};