longest common prefix

最大公共前缀

题目

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

If there is no common prefix, return an empty string “”.

解析重点

1.大概思路,先找出字符串数组,第一个和第二个字符串公共前缀,然后拿这个公共前缀和第三个字符串比较找出公共部分,依此类推

java代码

1
2
3
4
5
6
7
8
9
10
11
12
class  {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String prefix = strs[0];
for(int i = 1; i < strs.length; i++) {
while(strs[i].indexOf(prefix) != 0 && prefix.length() > 0) {
prefix = prefix.substring(0, prefix.length() - 1);
}
}
return prefix;
}
}