Question:
Write a function to find the longest common prefix string amongst an array of strings.
编写一个函数来查找字符串数组中最长的公共前缀字符串。
Answer:
找最长公共前缀呗。
思路是先让字符串数组字典排序,此时字符串数组就按照字符串长度由少到多的顺序排列了,那么能匹配到的最长公共前缀最大就是字符串数组的第一个字符串(或者比他要小)。
import java.util.Arrays;
public class Solution {
public String longestCommonPrefix(String[] strs){
if(strs.length==0) return "";
Arrays.sort(strs);
//for(String s: strs)
// System.out.println(s);
int count=1;
String str_temp = strs[0];
for(int i=1;i<=strs[0].length();i++){
while(count<strs.length){
//后面的字符是否含有str_temp字符串前缀,有则count+1比较下一字符串,没有则将str_temp缩减一位,再次比较。
if(strs[count].startsWith(str_temp)){
count++;
}
else {
count=1; //复位
str_temp = str_temp.substring(0,str_temp.length()-1);
break;
}
}
}
return str_temp;
}
}