题目: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"
.
注意:s.substr(i,j) 作用,从第i个位置开始,取出长度为j的子串。
方法一:递归(内存溢出)
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(wordDict.find(s)!=wordDict.end())
return true;
for(int i=0;i<s.size();i++)
{
if((wordDict.find(s.substr(0,i))!=wordDict.end())&&(wordBreak(s.substr(i+1,s.size()-1),wordDict)==true))
return true;
}
return false;
}
};
Submission Result: Time Limit Exceeded
Last executed input: