首页 > 其他 > 详细

14. 最长公共前缀

时间:2019-05-23 22:11:02      阅读:115      评论:0      收藏:0      [点我收藏+]

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

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

示例 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 }

 

14. 最长公共前缀

原文:https://www.cnblogs.com/xiyangchen/p/10914640.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!