Word Break
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".
解題思路:
解法1,回溯法。但會超時。其時間復雜度為len!
class Solution {
public:
bool wordBreak(string s, unordered_set& wordDict) {
return helper(s, wordDict);
}
bool helper(string s, unordered_set& wordDict){
if(s==""){
return true;
}
int len = s.length();
for(int i=1; i<=len; i++){
if(wordDict.find(s.substr(0, i))!=wordDict.end() && helper(s.substr(i), wordDict)){
return true;
}
}
return false;
}
};
解法2,動態規劃。對於d[i]表示字符串S[0,..., i]費否能夠被字典拼接而成。於是有
d[i] = true, 如果s[0,...i]在字典裡面
d[i] = true, 如果存在k,0
d[i] = false, 不存在這樣的k
代碼如下:
class Solution {
public:
bool wordBreak(string s, unordered_set& wordDict) {
int len = s.length();
if(len == 0){
return true;
}
bool d[len];
memset(d, 0, len * sizeof(bool));
if(wordDict.find(s.substr(0, 1)) == wordDict.end()){
d[0] = false;
}else{
d[0] = true;
}
for(int i=1; i時間復雜度為O(len^2)
另外,一個非常好的解法就是添加一個字符在s前面,使得代碼更加簡潔。
class Solution {
public:
bool wordBreak(string s, unordered_set& wordDict) {
s = "#" + s;
int len = s.length();
bool d[len];
memset(d, 0, len * sizeof(bool));
d[0] = true;
for(int i=1; i