-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestCommonPrefix.cpp
42 lines (39 loc) · 1.21 KB
/
longestCommonPrefix.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
/* https://leetcode.com/problems/longest-common-prefix/
* Write a function to find the longest common prefix string amongst an array
* of strings.
*/
class Solution {
public:
// recursion.
string longestCommonPrefix(vector < string > &strs) {
int size = strs.size();
if (size == 0)
return "";
if (size == 1)
return strs[0];
vector < string > sub(strs.begin() + 1, strs.end());
auto res_sub = longestCommonPrefix(sub);
int i;
for (i = 0; i < strs[0].size() && i < res_sub.size(); i++)
if (strs[0][i] != res_sub[i])
break;
return res_sub.substr(0, i);
}
// accpted for the first submit.
// non-recursion
string longestCommonPrefix2(vector < string > &strs) {
string res;
auto sz = strs.size();
if (0 == sz)
return res;
for (int i = 0; i < strs[0].size(); ++i) { // each char
char t = strs[0][i];
for (int j = 1; j < sz; ++j) { // each string
if (i >= strs[j].size() || t != strs[j][i])
return res;
}
res.push_back(t);
}
return res;
}
};