Skip to content

Commit 42583a5

Browse files
committed
longest_common_prefix.cpp
1 parent 0acb43c commit 42583a5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

longest_common_prefix.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
string longestCommonPrefix(vector<string>& strs) {
4+
if (strs.size() == 0)
5+
return string();
6+
if (strs.size() == 1)
7+
return strs[0];
8+
int minLen = longestCommonPrefix(strs[0], strs[1], -1);
9+
for (auto vit = strs.begin() + 1, nextit = strs.begin() + 2;
10+
nextit != strs.end(); ++vit, ++nextit)
11+
{
12+
int len = longestCommonPrefix(*vit, *nextit, minLen);
13+
if (len < minLen)
14+
minLen = len;
15+
}
16+
17+
18+
return string(strs[0], 0, minLen);
19+
}
20+
21+
int longestCommonPrefix(string& str1, string& str2, int len)
22+
{
23+
int result = 0;
24+
auto sit1 = str1.begin(), sit2 = str2.begin();
25+
for(int i = 0;
26+
sit1 != str1.end() && sit2 != str2.end() &&
27+
*sit1 == *sit2 && (i < len || len == -1);
28+
++sit1, ++sit2)
29+
{
30+
++result;
31+
}
32+
return result;
33+
}
34+
};

0 commit comments

Comments
 (0)