1、题目描述
2、题目分析
2-1、纵向扫描思路
纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。
class Solution {
public static String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
String common =strs[0];
int j = 0;
int len = strs[0].length();
for( ; j < len; j++){
for(int i = 1; i < strs.length; i++){
if( j > strs[i].length() -1
|| strs[i].charAt(j) != common.charAt(j))
return common.substring(0, j);
}
}
return common;
}
}
复杂度分析
时间复杂度:O(mn),其中 m 是字符串数组中的字符串的平均长度,n 是字符串的数量。最坏情况下,字符串数组中的每个字符串的每个字符都会被比较一次。
空间复杂度:O(1)。使用的额外空间复杂度为常数。
2-2、其他思路
当日也可以字符串两两比较,横向扫描思路等。