-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14.longest-common-prefix.cpp
More file actions
45 lines (37 loc) · 1 KB
/
14.longest-common-prefix.cpp
File metadata and controls
45 lines (37 loc) · 1 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
#include "testharness.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
int strsSize = strs.size();
size_t maxCommonLen = strs[0].size();
for (int j = 0; j < strsSize; j++) {
if (maxCommonLen > strs[j].size())
maxCommonLen = strs[j].size();
}
string result;
for (int i = 0; i < maxCommonLen; i++) {
bool flag = true;
for (int j = 0; j < strsSize - 1; ++j) {
if (strs[j][i] != strs[j+1][i]) {
flag = false;
break;
}
}
if (flag) {
result += strs[0][i];
} else {
return result;
}
}
return result;
}
};
TEST(Solution, test) {
ASSERT_EQ(2, 1+1);
}