-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestCommonPrefix.cc
84 lines (83 loc) · 1.96 KB
/
longestCommonPrefix.cc
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
string ret = "";
int n = strs.size();
if (!n) return ret;
int level = 0;
char cur;
while (strs[0][level] != '\0') {
cur = '\0';
for (int i = 0; i < n; i++) {
if (cur == '\0') cur = strs[i][level];
if (strs[i][level] == '\0' || cur != strs[i][level]) return ret;
}
ret += cur;
level++;
}
return ret;
}
//--------------------------------------------------//
string longestCommonPrefix(vector<string> &strs) {
if (!strs.size()) return "";
int i = 0;
string ret = "";
while (true) {
if (i >= strs[0].size())
break;
char ref;
ref = strs[0].at(i);
int j;
for (j = 1; j < strs.size(); ++j) {
if (strs[j].size() <= i)
break;
if (ref != strs[j][i])
break;
}
if (j == strs.size())
ret += ref;
else
break;
i++;
}
return ret;
}
/*string longestCommonPrefix(vector<string> &strs) {
string ret = "";
if (!strs.size())
return ret;
int i = 0;
while(true) {
string tmp; //string tmp = strs[0].at(i); won't work
if (strs[0].size() <= i)
break;
else
tmp = strs[0].at(i);
int j;
for (j = 1; j < strs.size(); ++j) {
if (strs[j].size() <= i)
break;
else if (strs[j].at(i) != *tmp.c_str())
break;
}
if (j == strs.size())
ret += tmp;
else
break;
i++;
}
return ret;
}*/
};
int main(int argc, char **argv) {
vector<string> strs;
strs.push_back("abcd");
strs.push_back("abc");
Solution sol;
cout << sol.longestCommonPrefix(strs) << endl;
return 0;
}