14. Longest Common Prefix

暴力破解

 1     public String longestCommonPrefix(String[] strs) {
 2         if(strs == null || strs.length == 0) {
 3             return "";
 4         }
 5         int min = minLen(strs);
 6         int cnt = 0;
 7         for(int i = 0; i < min; i++) {
 8             char c = strs[0].charAt(i);
 9             cnt++;
10             for(int j = 1; j < strs.length; j++) {
11                 if(strs[j].charAt(i) != c) {
12                     return strs[0].substring(0, cnt - 1);
13                 }
14             }
15         }
16         return strs[0].substring(0,cnt);
17     }
18     
19     private int minLen(String[] strs) {
20         int minLen = Integer.MAX_VALUE;
21         for(int i = 0; i < strs.length; i++) {
22             minLen = Math.min(minLen, strs[i].length());
23         }
24         return minLen;
25     }

 

posted @ 2016-01-28 07:38  warmland  阅读(116)  评论(0编辑  收藏  举报