P014 Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

思路分析

题目本身并不难,最直观的就是逐个字符比较。操作下标很费劲。

  • 最长前缀的长度不会超过某个字符串的长度

代码

java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution014 {
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder();
if (strs == null || strs.length == 0)
return "";
if (strs.length == 1)
return strs[0];
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (strs[j].length() == i || c != strs[j].charAt(i)) {
return sb.toString();
}
}
sb.append(c);
}
return sb.toString();
}
}

python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution014(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
l = len(strs)
if not strs or l == 0:return ""
if l == 1:return strs[0]
ret = ""
for i in range(0, len(strs[0])):
c = strs[0][i]
for j in range(1, l):
if len(strs[j]) == i or c != strs[j][i]:
return ret
ret += c;
return ret