14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
 1 public class LongestCommonPrefix {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs.length == 0) {
 4             return "";
 5         }
 6         if(strs.length == 1) {
 7             return strs[0];
 8         }
 9         int minLen = Integer.MAX_VALUE;
10         int temp = 0;
11         StringBuilder sb = new StringBuilder();
12         for(int i=0; i<strs.length; i++) {
13             temp = strs[i].length();
14             if(temp == 0) {
15                 return "";
16             }
17             if(temp < minLen) {
18                 minLen = temp;
19             }
20         }
21         for(int i=0; i<minLen; i++) {
22             for(int j=1; j<strs.length; j++)  {
23                 if(strs[0].charAt(i) != strs[j].charAt(i)){
24                     return sb.toString();
25                 }
26             }
27             sb.append(strs[0].charAt(i));
28         }
29         return sb.toString();
30     }
31 }

 

posted @ 2019-05-23 21:25  往南的小燕子  阅读(100)  评论(0编辑  收藏  举报