forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-common-prefix.cpp
56 lines (49 loc) · 1.28 KB
/
longest-common-prefix.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
// Time: O(n * k), k is length of the common prefix
// Space: O(1)
// BFS
class Solution {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0) {
return "";
}
auto prefix_len = strs[0].length();
for (int i = 0; i < prefix_len; ++i) {
for (const auto& str : strs) {
if (str[i] != strs[0][i]) {
prefix_len = i;
break;
}
}
}
return strs[0].substr(0, prefix_len);
}
};
// Time: O(n * l), l is the max length of strings
// Space: O(1)
// DFS
class Solution2 {
public:
/**
* @param strs: A list of strings
* @return: The longest common prefix
*/
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0) {
return "";
}
auto prefix_len = strs[0].length();
for (const auto& str : strs) {
auto i = 0;
for (; i < str.length() && i < prefix_len && str[i] == strs[0][i]; ++i);
if (i < prefix_len) {
prefix_len = i;
}
}
return strs[0].substr(0, prefix_len);
}
};