-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution14.h
65 lines (52 loc) · 1.31 KB
/
Solution14.h
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Author: huanglijun
// Date : 2019/5/27
// Desc :
//
#ifndef TESTCODE_SOLUTION14_H
#define TESTCODE_SOLUTION14_H
/*
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
*/
string longestCommonPrefix(vector<string>& strs) {
string retStr = "";
int num = 0;
while(true){
bool flag = true;
char c = '0';
for(vector<string>::iterator iter = strs.begin(); iter != strs.end(); iter++){
if(iter->size() < num + 1){
flag = false;
break;
} else {
if(c == '0'){
c = (*iter)[num];
} else {
if(c != (*iter)[num]){
flag = false;
break;
}
}
}
}
if(flag && c != '0'){
num++;
retStr += c;
} else {
break;
}
}
return retStr;
}
#endif //TESTCODE_SOLUTION14_H