-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_break.cpp
67 lines (60 loc) · 1.84 KB
/
word_break.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
*/
class Solution {
public:
map<string,int> dp;
bool check_dict(string s,vector<string>& wordDict)
{
//cout<<"checking dictionary"<<wordDict.size() <<"\n";
for(int i=0;i<wordDict.size();i++)
{
//cout<<s<<wordDict[i]<<s.compare(wordDict[i])<<"\n";
if(s.compare(wordDict[i])==0)
{
dp.insert(pair<string,int>(s,1));
return true;
}
}
dp.insert(pair<string,int>(s,0));
//cout<<"not found in dictionary\n";
return false;
}
bool wordBreak(string s, vector<string>& wordDict) {
if(wordDict.size()==0)
return false;
map<string,int> :: iterator itr;
itr=dp.find(s);
if(itr!=dp.end())
{
if(itr->second == 1)
return true;
else
return false;
}
else{
if(check_dict(s,wordDict))
{
return true;
}
if(s.length() == 1)
return false;
int n = s.length();
for(int i=0;i<n;i++)
{
string s1(s,0,i+1);
string s2(s,i+1,n-i-1);
if(wordBreak(s1,wordDict) && wordBreak(s2,wordDict))
{
dp.insert(pair<string,int>(s,1));
return true;
}
}
}
return false;
}
};