题目
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".
思路
这道题的主要思路就是动态规划,使用dp[i]来表示s[0,i]的字符串的一个是否可分割的情况,然后
则可以获取到对应的传递关系:
dp[i] = dp[j] && dp[j,i] ,其中 0<j<i;
因此就可以得出下列程序:
C/C++实现代码
class Solution {
public:
//使用动态规划,dp[i]表示s[0,i]这段字符串是否可以分割
//则dp[i] = dp[j] && dp[j+1,i]; 同时0<j<i;
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=0;j<i;j++){
if(dp[j] && dict.find(s.substr(j,i-j))!=dict.end()){
dp[i]=true;
break;
}
}
}
return dp[len];
}
};