LeetCode longest-common-prefix

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。 示例 1:

输入: ["flower","flow","flight"] 输出: "fl"

示例 2:

输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

解答:

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
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len = strs.size();
if (len == 0) {
return "";
}

if (len == 1) {
return strs[0];
}

string minStr = strs[0];
for (int i = 0; i < len; i++) {
if (strs[i].empty() || strs[0][0] != strs[i][0]) {
return "";
}

if (strs[i].length() <= minStr.length()) {
minStr = strs[i];
}
}

for (int i = 0; i < len; i++) {
if (minStr == strs[i]) {
continue;
}
for (int j = minStr.length()-1; j > 0 ; j--) {
if (minStr[j] != strs[i][j]) {
minStr = minStr.substr(0, j);
}
}
}
return minStr;
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×