Write a function to find the longest common prefix string amongst an array of strings.
/**
* 先排序数组,求所有字符串最长公共前缀,
* 只需求排序后的第一个字符串和最后一个字符串公共前缀
* Created by ustc-lezg on 16/4/6.
*/
public class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
Arrays.sort(strs);
String firstStr = strs[0];
String lastStr = strs[strs.length - 1];
int minLen = Math.min(firstStr.length(), lastStr.length());
int i = 0;
while (i < minLen && firstStr.charAt(i) == lastStr.charAt(i)) {
++i;
}
return firstStr.substring(0,i);
}
}