题目:
Write a function to find the longest common prefix string amongst an array of strings.
分析:典型题目。LCP问题,即找出字符串数组中最大公共前缀。思路为先找出前两个字符串的公共前缀,再找出该公共前缀与下一个字符串的公共前缀,以此类推,直到找出所有字符串的公共前缀。程序如下:
-
public class Solution {
-
public String longestCommonPrefix(String[] strs) {
-
int arrlen = strs.length;
-
String result = new String();
-
if(arrlen == 0){
-
return result;
-
}
-
result = strs[0];
-
for(int i = 1; i < arrlen; i++){
-
result = findCommonPrefix(result,strs[i]);
-
}
-
return result;
-
}
-
-
public String findCommonPrefix(String str1,String str2){
-
char[] charr1 = str1.toCharArray();
-
char[] charr2 = str2.toCharArray();
-
StringBuilder resultsb = new StringBuilder();
-
int i = 0;
-
int str1len = str1.length();
-
int str2len = str2.length();
-
while(i < str1len && i < str2len && charr1[i] == charr2[i]){
-
i++;
-
}
-
for(int j = 0; j < i; j++){
-
resultsb.append(charr1[j]);
-
}
-
return resultsb.toString();
-
}
-
}
阅读(1088) | 评论(0) | 转发(0) |