leetcode-14-字符串题-最长公共前缀

题目

1.png

解法

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
// 水平扫描,以第一个字符串为标准,依次比对后面的字符串
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
string result;
int vecSize = int(strs.size());
if (vecSize == 0)
{
return result;
}
if (vecSize == 1)
{
return strs[0];
}
int min = INT_MAX;
//获得最小长度
for (int index = 0; index < vecSize; ++index)
{
int strSize = strs[index].size();
if (min > strSize)
{
min = strSize;
}
}

for (int increment = 1; increment <= min; ++increment)
{
string test = strs[0].substr(0, increment);
for (int index = 1; index < vecSize; ++index)
{
string compared = strs[index].substr(0, increment);
if (test != compared)
{
increment--;
result = strs[0].substr(0, increment);
return result;
}
}
}

result = strs[0].substr(0, min);
return result;
}
};