2020/09/04 1.用二维数组,慢 2.每一列比较,都要比较到最后,慢
初解思路
第一反应就是二维数组,纵向对比。
关于对比方式,想到了char累加,平均等于第一个数组里的值即可(实际上第一个数组里的值等于平均值的话,就出错了。比如[“b”,“a”,“c”])。
乖乖采取挨个对比。
结果:11ms 39.9M --------------- (ΩДΩ)
再想想吧
Code
public class LongestCommonPrefix {
public String
longestCommonPrefix(String
[] strs
) {
String res
= "";
int width
= strs
.length
;
if(width
==0) return res
;
char[][] arr
= new char[width
][];
for(int i
=0;i
<width
;i
++){
if(strs
[i
].length()==0) return res
;
arr
[i
] = strs
[i
].toCharArray();
}
int j
= 0;
while(j
>=0){
int count
= 0;
if(j
>arr
[0].length
-1){
return res
;
}
char first
= arr
[0][j
];
for(int p
=0;p
<width
;p
++){
if(j
>arr
[p
].length
-1){
return res
;
}
count
+=(arr
[p
][j
]==first
?1:0);
}
if(count
==width
){
res
+=first
;
j
++;
}else{
j
= -1;
}
}
return res
;
}
public static void main(String
[] args
) {
LongestCommonPrefix lcp
= new LongestCommonPrefix();
String
[] strs
= {"flower","fla","flc"};
System
.out
.println(lcp
.longestCommonPrefix(strs
));
}
}