-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestCommonPrefix.cpp
More file actions
115 lines (90 loc) · 2.44 KB
/
longestCommonPrefix.cpp
File metadata and controls
115 lines (90 loc) · 2.44 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
using namespace std;
// struct Node
// {
// Node*list[26];
// bool flag = false;
// int cntPrefix = 0;
// bool containsKey(char ch) {
// return list[ch - 'a'] != NULL;
// }
// void put(char ch, Node* node) {
// list[ch - 'a'] = node;
// }
// Node* get(char ch) {
// return list[ch - 'a'];
// }
// void increasePrefix() {
// cntPrefix++;
// }
// void setEnd() {
// flag = true;
// }
// bool isEnd() {
// return flag;
// }
// };
// class Trie {
// private:
// Node* root;
// public:
// Trie() {
// root = new Node();
// }
// void insert(string word) {
// Node*node = root;
// for(int i = 0; i < word.length(); i++) {
// if(!node->containsKey(word[i])){
// node->put(word[i], new Node());
// }
// node = node->get(word[i]);
// node->increasePrefix();
// }
// node->setEnd();
// }
// string longestCommonPrefix(string word, int n) {
// Node*node = root;
// string ans = "";
// for(auto c : word) {
// if(node->containsKey(c)) {
// node = node->get(c);
// if(node->cntPrefix == n) {
// ans = ans + c;
// }
// else break;
// } else break;
// }
// return ans;
// }
// };
// string longestCommonPrefix(vector<string> &arr, int n)
// {
// // Write your code here
// auto it = max_element(arr.begin(), arr.end(),
// [](const string &a, const string &b) {
// return a.size() < b.size();
// });
// Trie trie;
// for(int i = 0; i < arr.size(); i++) {
// trie.insert(arr[i]);
// }
// return trie.longestCommonPrefix(*it, n);
// }
// this is more optimised solution than the previous one
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
for (int i = 0; i < strs[0].size(); ++i) {
char c = strs[0][i];
for (int j = 1; j < strs.size(); ++j) {
if (i == strs[j].size() || strs[j][i] != c) {
return strs[0].substr(0, i);
}
}
}
return strs[0];
}
int main() {
vector<string> arr = {"coder", "codingninja", "coding","code","codable"};
cout << longestCommonPrefix(arr) << endl;
return 0;
}