您的位置:首页 > 其它

leetcode-14-求字符串数组最长公共前缀

2017-05-15 21:16 453 查看
String的compareTo方法是按照字典顺序比较的。而Arrays.sort方法对对象数组按照自然顺序进行排序。

public static void sort(Object[] a) 该方法要求数组元素实现了Comparable接口,所以如果是对字符串数组进行排序,是按照字典顺序进行排序的。

public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
StringBuffer res = new StringBuffer();
Arrays.sort(strs);
String s1 = strs[0], s2 = strs[strs.length - 1];
for (int i = 0; i < s1.length(); i++) {
if (s2.length() > i && s2.charAt(i) == s1.charAt(i))
res.append(s1.charAt(i));
else return res.toString();
}
return res.toString();
}


先对数组进行排序,如果存在公共前缀,第一个元素的前缀一定也是最后一个元素的前缀,如果不是,则没有公共前缀。如果是,就不断增加字符,直到最大的公共前缀。

注意这里strs中如果有空字符串,那么排序后这个空字符串位于第一个元素,结果返回一个空字符串。因为空字符串没有公共前缀。

例如对
String[] str = " and then you can simply compare the first and last elements in the sorted array".split(" ");
进行排序,结果为

//这是个空字符串
and
and
array
can
compare
elements
first
in
last
simply
sorted
the
the
then
you


分析左侧第一个字符,如果是公共前缀,那么第一个和最后一个的第一个应该一样。如果不是,那就没有公共前缀,返回一个空字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: