-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLongestCommonPrefixMethod3.cpp
83 lines (67 loc) · 2 KB
/
LongestCommonPrefixMethod3.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
class TrieNode
{
public:
bool isLeaf;
std::unordered_map<char, TrieNode*> next;
TrieNode() {
isLeaf = false;
}
};
class Trie
{
private:
TrieNode* root;
public:
Trie() : root { nullptr }
{ }
void insert(std::string const& str) {
if (root == nullptr) {
root = new TrieNode();
}
TrieNode* current = root;
for (char ch : str) {
if (current->next.find(ch) == current->next.end()) {
current->next[ch] = new TrieNode();
}
current = current->next[ch];
}
current->isLeaf = true;
}
std::string findPrefix() {
if (root == nullptr) {
return "";
}
TrieNode* current = root;
std::string lcp;
while (current != nullptr && current->isLeaf != true && current->next.size() == 1) {
auto it = current->next.begin();
lcp += it->first;
current = it->second;
}
return lcp;
}
};
std::string longestCommonPrefix(std::vector<std::string>& strs)
{
Trie trie;
for (auto& str : strs) {
trie.insert(str);
}
std::string result = trie.findPrefix();
return result;
}
int main()
{
std::vector<std::string> strs {"flower","flow","flight"};
std::cout << "Longest Common Prefix : " << longestCommonPrefix(strs) << std::endl;
std::vector<std::string> strs2 {"code", "coder", "coding", "codable", "codec", "codecs", "coded",
"codeless", "codependence", "codependency", "codependent",
"codependents", "codes", "codesign", "codesigned", "codeveloped",
"codeveloper", "codex", "codify", "codiscovered", "codrive"};
std::cout << "Longest Common Prefix : " << longestCommonPrefix(strs2) << std::endl;
}