Skip to content

Commit ce4ee78

Browse files
committed
14 Longest Common Prefix
1 parent 4d6891d commit ce4ee78

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
+ [9 Palindrome Number](algorithms/PalindromeNumber)
99
+ [10 Regular Expression Matching(递归)](algorithms/RegularExpressionMatching)
1010
+ [11 Container With Most Water](algorithms/ContainerWithMostWater)
11+
+ [14 Longest Common Prefix](algorithms/LongestCommonPrefix)
1112
+ [15 3Sum](algorithms/3Sum)
1213
+ [17 Letter Combinations of a Phone Number](algorithms/LetterCombinationsofaPhoneNumber)
1314
+ [18 4Sum](algorithms/4Sum)
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
## Longest Common Prefix
2+
3+
Write a function to find the longest common prefix string amongst an array of strings.
4+
5+
## Solution
6+
7+
逐一比较即可
8+
```cpp
9+
string longestCommonPrefix(vector<string>& strs) {
10+
int n = strs.size();
11+
if (n < 1)
12+
return "";
13+
int m = strs[0].size();
14+
int i,j;
15+
for (i = 0; i < m; ++i) {
16+
for (auto s : strs) {
17+
if (i >= s.size() || s[i] != strs[0][i])
18+
return strs[0].substr(0, i);
19+
}
20+
}
21+
return strs[0];
22+
}
23+
```
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <string>
2+
#include <iostream>
3+
#include <cstdio>
4+
#include <vector>
5+
using namespace std;
6+
class Solution {
7+
public:
8+
string longestCommonPrefix(vector<string>& strs) {
9+
int n = strs.size();
10+
if (n < 1)
11+
return "";
12+
int m = strs[0].size();
13+
int i,j;
14+
for (i = 0; i < m; ++i) {
15+
for (auto s : strs) {
16+
if (i >= s.size() || s[i] != strs[0][i])
17+
return strs[0].substr(0, i);
18+
}
19+
}
20+
return strs[0];
21+
}
22+
23+
};
24+
int main(int argc, char **argv)
25+
{
26+
Solution solution;
27+
vector<string> s = {"abcd", "abc", "abedefg", "abcdefgh"};
28+
cout << solution.longestCommonPrefix(s) << endl;
29+
}

0 commit comments

Comments
 (0)