class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
auto words = unordered_set<string>();
for(auto word : wordDict){
words.insert(word);
}
auto dp = vector<bool>(s.size() + 1); //整体往后一位,所以要多加1个长度
dp[0] = true;
for(int i = 1; i <= s.size(); ++i){
for(int j = 0; j < i; ++j){
if(dp[j] //前面都已经配对上了
&& words.count(s.substr(j, i - j))){ //目前检索的这段也配对上了
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};
Accepted
45/45 cases passed (12 ms)
Your runtime beats 63.27 % of cpp submissions
Your memory usage beats 48.98 % of cpp submissions (12.8 MB)