Skip to content

Commit 25a4ae6

Browse files
committed
Progress: 21/150 - Method 2 Done
1 parent b19604a commit 25a4ae6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

cpp/021#LongestCommonPrefix2.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// 纵向扫描
2+
// Time Complexity: O(m*n)
3+
// Space Complexity: O(1)
4+
5+
# include <iostream>
6+
# include <vector>
7+
# include <string>
8+
using namespace std;
9+
10+
class Solution {
11+
public:
12+
string longestCommonPrefix(vector<string>& strs) {
13+
if (!strs.size()) {
14+
return "";
15+
}
16+
// 以第一个字符串为基准
17+
int length = strs[0].size();
18+
// 字符串个数
19+
int count = strs.size();
20+
for (int i = 0; i < length; ++i) {
21+
char c = strs[0][i];
22+
for (int j = 1; j < count; ++j) {
23+
// 如果当前字符不相等或者已经到达某个字符串的末尾
24+
if (i == strs[j].size() || strs[j][i] != c) {
25+
return strs[0].substr(0, i);
26+
}
27+
}
28+
}
29+
return strs[0];
30+
}
31+
};
32+
33+
int main() {
34+
Solution solution;
35+
vector<string> strs = {"flower", "flow", "flight"};
36+
cout << solution.longestCommonPrefix(strs) << endl;
37+
return 0;
38+
}

0 commit comments

Comments
 (0)