-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLong Common Prefix.cpp
More file actions
37 lines (33 loc) · 864 Bytes
/
Long Common Prefix.cpp
File metadata and controls
37 lines (33 loc) · 864 Bytes
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
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (strs.size() <= 0)
return "";
string commonPrefix = strs[0];
int i = 0;
for (i = 1; i < strs.size(); i++)
{
commonPrefix = getCommonPrefix(commonPrefix,strs[i]);
}
return commonPrefix;
}
string getCommonPrefix(string str1,string str2)
{
string str = "";
int i = 0;
for (i = 0; i < str1.size() && i < str2.size(); i++)
{
if (str1[i] == str2[i])
{
str += str1[i];
}
else
{
break;
}
}
return str;
}
};