File tree 1 file changed +62
-0
lines changed
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ vector<int > dp;// for memorization of strings which can be formed using dictionary
5
+ int func (string A,set<string> s)
6
+ {
7
+ int n=A.length ();
8
+ dp.resize (n,0 );
9
+ for (int i=0 ;i<n;i++)
10
+ {
11
+ string temp=" " ;
12
+ for (int j=i;j>=0 ;j--)// Checking for all possible strings before the present string which can form this string
13
+ {
14
+ temp+=A[j];
15
+ if (j==0 )
16
+ {
17
+ if (s.find (temp)!=s.end ())
18
+ {
19
+ dp[i]=1 ;// If string can be formed
20
+ break ;
21
+ }
22
+ }
23
+ else
24
+ {
25
+ if ((s.find (temp)!=s.end ())&&(dp[j-1 ]==1 ))
26
+ {
27
+ dp[i]=1 ;
28
+ break ;
29
+ }
30
+ }
31
+ }
32
+ }
33
+ int val=dp[n-1 ];
34
+ dp.clear ();
35
+ return val;
36
+ }
37
+
38
+ int wordBreak (string A, vector<string> &B) {
39
+ set<string> s;
40
+ for (int i=0 ;i<B.size ();i++)
41
+ {
42
+ string temp=B[i];
43
+ reverse (temp.begin (),temp.end ());
44
+ s.insert (temp);// Storing reverse of the dictionary words to make search easier in next function
45
+ }
46
+ return func (A,s);
47
+ }
48
+
49
+ int main ()
50
+ {
51
+ int n;
52
+ cin>>n;// No of words in dictionary
53
+ string A;// Main word
54
+ vector<string> B (n);// Words in dictionary
55
+ cin>>A;
56
+ for (int i=0 ;i<n;i++)
57
+ {
58
+ cin>>B[i];
59
+ }
60
+ cout<<wordBreak (A,B)<<endl;// This will tell whether the main word can be formed using combination of dictionary words
61
+ return 0 ;
62
+ }
You can’t perform that action at this time.
0 commit comments