Write a function to find the longest common prefix string amongst an array of strings.

求最长公共前缀:以第一个字符串为模板比较之后的字符串即可。

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         int len=strs.length;
 4         if(len==0) return "";
 5         if(len==1) return strs[0];
 6         int l=strs[0].length();
 7         int i=0;
 8         String ans="";
 9         while(i<l){
10             for(int j=0;j<len;j++){
11                 if(strs[j].length()<=i)
12                    return ans;
13                 if(strs[0].charAt(i)!=strs[j].charAt(i))
14                    return ans;
15                 
16             }
17             ans+=strs[0].charAt(i);
18             i++;
19         }
20         
21         return ans;
22     }
23 }
View Code

 

posted on 2015-06-06 10:12  gone~with~wind  阅读(104)  评论(0)    收藏  举报