-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14.最长公共前缀.cpp
42 lines (39 loc) · 996 Bytes
/
14.最长公共前缀.cpp
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
/*
* @lc app=leetcode.cn id=14 lang=cpp
*
* [14] 最长公共前缀
*/
#include <iostream>
#include <vector>
using namespace std;
// @lc code=start
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int size = strs.size();
if(size == 0){
return "";
}else if(size == 1){
return strs[0];
}
string prefix = "";
for(int i = 0; ; i++){
char ch;
for(int j = 0; j < size; j++){ // 比较str[j][i]
if(j == 0){
if(i >= strs[j].size()){
return prefix;
}
ch = strs[j][i];
continue;
}
if(i >= strs[j].size() || ch != strs[j][i]){
return prefix;
}
}
prefix += ch;
}
return prefix;
}
};
// @lc code=end