-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Word formed by other words
73 lines (66 loc) · 2.3 KB
/
Longest Word formed by other words
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
68
69
70
71
72
73
/*
You are given an array ‘ARR’ consisting of ‘N’ strings. Your task is to find the longest common prefix among all these strings.
If there is no common prefix, you have to return an empty string.
A prefix of a string can be defined as a substring obtained after removing some or all characters from the end of the string.
For Example:
Consider ARR = [“coding”, ”codezen”, ”codingninja”, ”coders”]
The longest common prefix among all the given strings is “cod” as it is present as a prefix in all strings. Hence, the answer is “cod”.
Sample Input 1 :
5
test
tester
testertest
testing
testingtester
Sample Output 1 :
testingtester
Explanation Of Sample Input 1 :
Here in the given list of words, you can see that the word ‘testingtester’ contains both the words present in the list i.e. testing and tester.
Sample Input 2 :
11
cat
banana
dog
nana
my
walk
walker
baby
dogwalkers
s
babymybaby
Sample Output 2 :
babymybaby dogwalkers
*/
Approach:
traverse all words, if breakable into other words of the dictionary then update the maxlength accordingly, if max length then add to answer.
to check for every partition possible, proceed via recursion.
#include <bits/stdc++.h>
bool isBreakable(string &word, int startIn, unordered_set<string>&wordHash){
if(startIn == word.length()) return true;
for(int i=startIn;i<word.length();++i){
string sub = word.substr(startIn, i+1-startIn);
if(sub.length()!=word.length() && wordHash.find(sub)!=wordHash.end()){
if(isBreakable(word, i+1, wordHash)) return true;
}
}
return false;
}
bool comp(string &s1, string &s2) { return s1.length()>=s2.length();}
vector<string> findLongestWordList(vector<string>& wordList){
unordered_set<string>wordHash(wordList.begin(), wordList.end());
sort(wordList.begin(),wordList.end(),comp);
int ansL = 0;
vector<string>ans;
for(string &word : wordList){
if(word.length()>=ansL && isBreakable(word,0,wordHash)){
ansL = word.length();
ans.push_back(word);
}
}
sort(ans.begin(),ans.end());
return ans;
}
//T.C. : O(N * 2*(wl-1)) : N number of words(we are traversing) and for each word, we can put max into wl-1 cuts, and at every point have a choice of cut
hence 2^(wl-1)
//S.C. : O(N) for extra hash and exponential for recursion having substrings