[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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM