File tree 3 files changed +53
-0
lines changed
algorithms/LongestCommonPrefix
3 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 8
8
+ [ 9 Palindrome Number] ( algorithms/PalindromeNumber )
9
9
+ [ 10 Regular Expression Matching(递归)] ( algorithms/RegularExpressionMatching )
10
10
+ [ 11 Container With Most Water] ( algorithms/ContainerWithMostWater )
11
+ + [ 14 Longest Common Prefix] ( algorithms/LongestCommonPrefix )
11
12
+ [ 15 3Sum] ( algorithms/3Sum )
12
13
+ [ 17 Letter Combinations of a Phone Number] ( algorithms/LetterCombinationsofaPhoneNumber )
13
14
+ [ 18 4Sum] ( algorithms/4Sum )
Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments