Write a function to find the longest common prefix string amongst an array of strings.
[]
=>""
["abcweed","htgdabc","sabcrf"]
=>""
["abcweed","abhtgdc","abacrf"]
=>"ab"
题目大意:求字符串数组的最长子前缀
public class Solution{
public String longestCommonPrefix(String[] strs) {
//System.out.println(Arrays.toString(strs));
if(strs.length == 0)
return "";
int min = Integer.MAX_VALUE;
for(String s : strs){
if(min>s.length())
min = s.length();
}
if(min==0)
return "";
//System.out.println(min);
String prefix = "", tmp = "";
int i=0;
for( ; i<min; i++){
prefix = strs[0].substring(0,(i+1));
//System.out.println("prefix=" + prefix);
for(int j=1; j<strs.length; j++){
tmp = strs[j].substring(0,(i+1));
//System.out.println("tmp=" + tmp);
if(!prefix.equals(tmp))
return strs[0].substring(0,(i));
}
}
System.out.println("i=" + strs[0].substring(0,(i)));
return "";
} public static void main(String[] args){
String[] arr = {"","asdffg","aswd"};
if(args.length!=0)
arr = args;
Solution solution = new Solution();
String res = solution.longestCommonPrefix(arr);
System.out.println(res);
}
}