14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
题目大意:求一组字符串的最长前缀。
代码如下:
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
|
class
Solution {
public
:
string longestCommonPrefix(vector<string>& strs) {
if
(strs.size() == 0)
return
""
;
int
minStrLen = strs[0].size();
string result;
for
(
int
i = 0 ;i < strs.size();i++)
{
if
(strs[i].size() < minStrLen)
{
minStrLen = strs[i].size();
}
}
int
i = 0;
for
( ; i < minStrLen;i++)
{
char
a = strs[0][i];
int
j = 0;
for
( ;j < strs.size();j++)
{
if
(strs[j][i] != a)
break
;
}
if
(j < strs.size())
break
;
}
result = strs[0].substr(0,i);
return
result;
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836612