-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path014_CommonPrefix.cpp
60 lines (55 loc) · 1.25 KB
/
014_CommonPrefix.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
//Boundary conditions check
int size = strs.size();
if(0 == size)
return "";
if(1 == size)
return strs[0];
bool flag = true;
int sizeFirst = strs[0].size();
int pos = 0;
for(pos = 0; pos < sizeFirst; pos++)
{
char charFirst = strs[0][pos];
for(int indexStrs = 1; indexStrs < size; indexStrs++)
if(pos >= strs[indexStrs].size() || strs[indexStrs][pos] != charFirst)
{
flag = false;
break;
}
if(!flag)
break;
}
return strs[0].substr(0, pos);
}
};
//17.11%
class Solution001 {
public:
string longestCommonPrefix(vector<string>& strs) {
//Boundary conditions check
int size = strs.size();
if(0 == size)
return "";
if(1 == size)
return strs[0];
bool flag = true;
int sizeFirst = strs[0].size();
int pos = 0;
for(pos = 0; pos < sizeFirst; pos++)
{
char charFirst = strs[0][pos];
for(int indexStrs = 1; indexStrs < size; indexStrs++)
if(pos >= strs[indexStrs].size() || strs[indexStrs][pos] != charFirst)
{
flag = false;
break;
}
if(!flag)
break;
}
return strs[0].substr(0, pos);
}
};