[JAVA]寻找最长公共前缀

法1:来源leetcode

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         String ret = "";
 4         
 5         if(strs.length == 0) return ret;
 6         if(strs.length == 1) return strs[0];
 7         
 8         ret = strs[0];
 9         
10         for(int i = 1; i < strs.length; i++){
11             while (!strs[i].startsWith(ret)){
12                 ret = ret.substring(0, ret.length()-1);
13                 if (ret.length() == 0){
14                     return "";
15                 }
16             }
17         }
18         return ret;
19     }
20 }

法2:来源我

 1 class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs.length==0) return "";
 4         String s=new String();
 5         int i=0,j=1;
 6         while(true)
 7         {
 8             if(i>=strs[0].length()) return s;
 9             char t=strs[0].charAt(i);
10             for(j=1;j<strs.length;++j)
11             {
12                 if(i>=strs[j].length()||strs[j].charAt(i)!=t) break;
13             }
14             ++i;
15             if(j==strs.length) s+=t;
16             else return s;
17         }
18     }
19 }

 

posted @ 2018-11-30 11:58  jm_epiphany  阅读(1077)  评论(0编辑  收藏  举报