1.代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int length = s.size();
bool *count1 = new bool[length+1];
fill(count1, count1 + length + 1, false);
unordered_map<string, bool> hashTable;
count1[0] = true;
for(int i = 0;i < wordDict.size();i ++){
hashTable[wordDict[i]] = true;
}
for(int i = 1;i <= length;i ++){
for(int j = 0;j < i;j ++){
if(count1[j] && hashTable.count(s.substr(j,i-j))>0){
count1[i] = true;
break;
}
}
}
return count1[length];
}
};
2.思路
用了动态规划,用一个count1数组记录字符串的前i个字母是否能拆分成单词,状态转移方程是count1[i] = count1[j] &&hashTable.count(s.substr(j,i-j))>0。