我的解法
暴力法(垂直扫描法)
求得字符串长度的最小值,最长公共前缀的长度一定不会超过这个最小值 minLen
从第一个字符串依次取 minLen
个字符,每取一个字符就看其余字符串的同一位置是否是该字符,若所有字符串的同一位置都是该字符,将其加入到结果串 com
中,否则,退出循环,该字符前面的部分即为最大前缀串。
class Solution {
public String longestCommonPrefix(String[] strs) {
String com = "";
int minLen = 200;
for(int i = 0;i < strs.length;++i)
minLen = strs[i].length() < minLen ? strs[i].length() : minLen;
for(int i = 0;i < minLen;++i){
char tmp = strs[0].charAt(i);
int j;
for(j = 0;j < strs.length;++j)
if(strs[j].charAt(i) != tmp)
break;
if(j == strs.length)
com += tmp;
else
break;
}
return com;
}
}
题解
水平扫描法
假设第一个字符串为结果串,用结果串和后续的字符串依次比较,后续的字符串不是以 com
为前缀,则结果串长度减一,直至结果串为所有后续字符串的前缀或者返回 ""
若字符串 com
是 str
的前缀,则 str.indexOf(com) == 0
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String com = strs[0];
for(int i = 1;i < strs.length;++i){
while(strs[i].indexOf(com) != 0){
com = com.substring(0,com.length()-1);
if(com.length() == 0)
return "";
}
}
return com;
}
}
字典序
字典序这个点没有想到,排成字典序,第一个和最后一个的公共前缀就是这个字符串组的最大公共前缀
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
if(strs.length == 1)
return strs[0];
Arrays.sort(strs,new Cmp());
String com = strs[0];
//当有多个最短字符串,则都需要比较
int i = 1;
while(i != strs.length && strs[i].length() == strs[0].length()){
while(strs[i].indexOf(com) != 0){
com = com.substring(0,com.length()-1);
}
i++;
}
//当有多个最长字符
int j = strs.length-2;
while(j != 0 && strs[j].length() == strs[strs.length-1].length()){
while(strs[j].indexOf(com) != 0){
com = com.substring(0,com.length()-1);
}
j--;
}
for(int k = 0;k < strs.length;++k)
while(strs[k].indexOf(com) != 0){
com = com.substring(0,com.length()-1);
if(com.length() == 0)
return "";
}
return com;
}
}
class Cmp implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
// TODO 自动生成的方法存根
return o1.length() - o2.length();
}
}
。。。。。。终于是过了
java排序补充
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
private List<Type> list = new ArrayList<>();
Collections.sort(list, new Comparator<Type>() {
@Override
public int compare(Type o1, Type o2) {
return o1.compareTo(o2);// o1>o2
}
});
//倒序排列
Collections.reverse(list);
问题
没想到字典序,还是刷题基础不牢,像位运算,回文串,排序,查找这些基础没练习过,需要从简单的入手,练好基础再来刷这些题就不止 O ( n 2 ) O(n^2) O(n2) 了
感受就是做好一道题比多做几道简单题有用。