标签:res 字符 ++ for private str 第一个 ref longest
一、Description:
Write a function to find the longest common prefix string amongst an array of strings.
public class Solution {
public String longestCommonPrefix(String[] strs) {
}
}
二、Solutions:
1、思路:
开始想的是数组中每两个相邻字符串进行比较,并取比较的最短的前缀作为整个数组的最短前缀。时间复杂度为 n^2
public static String longestCommonPrefix(String[] strs) {
if(strs.length == 0) return "";
int len , commonLen = strs[0].length();
for (int i = 0; i < strs.length - 1; i++) {
len = getCommonPrefix(strs[i], strs[i+1]);
if(commonLen > len) commonLen = len;
}
return strs[0].substring(0, commonLen);
}
private static int getCommonPrefix(String str1, String str2) {
int result = 0;
for (int i = 0; i < str1.length() && i < str2.length(); i++) {
if(str1.charAt(i) == str2.charAt(i))
result++;
else
break;
}
return result;
}
2、优化:
以第一个字符串作为公共前缀prefix,依次作为第2个字符串的前缀进行比较,若不符合,则prefix长度-1.. ;符合则再与第3个字符串进行比较...时间复杂度m*n
public static String longestCommonPrefix2(String[] strs) {
if(strs == null || strs.length == 0) return "";
int i = 1;
String prefix = strs[0];
while (i < strs.length) {
while (strs[i].indexOf(prefix) == -1)
prefix = prefix.substring(0, prefix.length() - 1);
if(prefix == "")
return "";
i++;
}
return prefix;
}
14. Longest Common Prefix (最长公共前缀)
标签:res 字符 ++ for private str 第一个 ref longest
原文地址:http://www.cnblogs.com/skillking/p/6886489.html