File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ PROBLEM:
2+
3+ Implement a trie with insert, search, and startsWith methods.
4+
5+ Example:
6+ Trie trie = new Trie();
7+
8+ trie.insert(" apple" );
9+ trie.search(" apple" ); // returns true
10+ trie.search(" app" ); // returns false
11+ trie.startsWith(" app" ); // returns true
12+ trie.insert(" app" );
13+ trie.search(" app" ); // returns true
14+
15+ Note:
16+ You may assume that all inputs are consist of lowercase letters a-z.
17+ All inputs are guaranteed to be non-empty strings.
18+
19+
20+
21+ SOLUTION:
22+
23+
24+ class Trie {
25+ private:
26+ unordered_set<string> s,s1;
27+ public:
28+ /* * Initialize your data structure here. */
29+ Trie () {
30+
31+ }
32+
33+ /* * Inserts a word into the trie. */
34+ void insert (string word) {
35+ s.insert (word);
36+
37+ string m=" " ;
38+ for (int i=0 ;i<word.size ();i++)
39+ {
40+ m+=word[i];
41+ s1.insert (m);
42+ }
43+
44+ }
45+
46+ /* * Returns if the word is in the trie. */
47+ bool search (string word) {
48+
49+ if (s.find (word)!=s.end ())
50+ return true ;
51+ else
52+ return false ;
53+
54+ }
55+
56+ /* * Returns if there is any word in the trie that starts with the given prefix. */
57+ bool startsWith (string prefix) {
58+
59+ if (s1.find (prefix)!=s1.end ())
60+ return true ;
61+ else
62+ return false ;
63+
64+
65+ }
66+ };
67+
68+ /* *
69+ * Your Trie object will be instantiated and called as such:
70+ * Trie* obj = new Trie();
71+ * obj->insert(word);
72+ * bool param_2 = obj->search(word);
73+ * bool param_3 = obj->startsWith(prefix);
74+ */
You can’t perform that action at this time.
0 commit comments