代码一、使用递归算法,超时
class Solution {
public:
/*
* @param s: A string
* @param dict: A dictionary of words dict
* @return: A boolean
*/
bool wordBreak(string &s, unordered_set<string> &dict) {
// write your code here
return dp(s,dict,0);
}
bool dp(string &s,unordered_set<string> &dict,int p){
bool ans=false;
if(p==s.size()) return true;
for(int i=p;i<s.size();i++){
if(dict.count(s.substr(p,i-p+1))!=0) ans=max(ans,dp(s,dict,i+1));
}
return ans;
}
};
代码二、暴力破解双重循环O(n平方),超时
class Solution {
public:
/*
* @param s: A string
* @param dict: A dictionary of words dict
* @return: A boolean
*/
bool wordBreak(string &s, unordered_set<string> &dict) {
// write