Write a function to find the longest common prefix string amongst an array of strings.
编写一个函数来查找字符串数组中最长的公共前缀字符串。
代码
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) return "";
String pre = strs[0];
int i = 1;
while(i < strs.length){
while(strs[i].indexOf(pre) != 0)
pre = pre.substring(0,pre.length()-1);
i++;
}
return pre;
}
这里的思路是:
首先求2个的最长公共长缀,再用这个长缀去求第3个的最长公共长缀….
本文介绍了一种用于寻找字符串数组中最长公共前缀的方法。通过不断缩小比较范围,该算法能够高效地找到所有字符串共有的最长起始部分。
687

被折叠的 条评论
为什么被折叠?



