Skip to content

Commit 63a8c49

Browse files
committed
Longest Common Prefix
1 parent 899ec3a commit 63a8c49

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

14.cpp

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
string longestCommonPrefix(vector<string>& strs) {
4+
if (strs.empty()) {
5+
return "";
6+
}
7+
8+
string prefix = "";
9+
int p = 0;
10+
int size = strs.size();
11+
bool loop = true;
12+
13+
while (loop) {
14+
char c = '\0';
15+
for (int i = 0; i < size; ++i) {
16+
if (p >= strs[i].size()) {
17+
loop = false;
18+
break;
19+
}
20+
21+
if (c == '\0') {
22+
c = strs[i][p];
23+
}
24+
else if (c == strs[i][p]) {
25+
continue;
26+
}
27+
else {
28+
loop = false;
29+
break;
30+
}
31+
}
32+
if (loop) {
33+
prefix.push_back(c);
34+
++p;
35+
}
36+
}
37+
return prefix;
38+
}
39+
};

0 commit comments

Comments
 (0)