题目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
- 题意:找出字符串的最大的公共前缀
- 思路是写一个比较的函数,遍历
-
代码:
public class Solution {
public String longestCommonPrefix(String[] strs) {
String result = null;
if(strs == null){
return null;
}
if(strs.length == 0){
return "";
}
if(strs.length == 1){
return strs[0];
}
result = see(strs[0],strs[1]);
if(result == null){
return null;
}
for(int a= 1;a < strs.length-1;a++){
String tmp = see(strs[a],strs[a+1]);
if(tmp == null){
return null;
}else{
String tmp1 = see(tmp,result);
if(tmp1 == null){
return null;
}else{
result = tmp1;
}
}
}
return result;
}
public String see(String a,String b){
StringBuffer sb = new StringBuffer();
if(a == null || b == null){
return null;
}
int n = Math.min(a.length(),b.length());
for(int i = 0;i < n;i++){
if(a.charAt(i) == b.charAt(i)){
sb.append(a.charAt(i));
}else{
return sb.toString();
}
}
return sb.toString();
}
}