首页 > 其他 > 详细

【Leetcode-easy】Longest Common Prefix

时间:2015-11-20 18:54:39      阅读:185      评论:0      收藏:0      [点我收藏+]

思路:每次从字符数组中读取两个字符串比较。需要注意输入字符串为空,等细节。

 1     public String longestCommonPrefix(String[] strs) {
 2         if(strs==null||strs.length==0){
 3             return "";
 4         }
 5         int count=strs[0].length();
 6         for(int i=1;i<strs.length;i++){
 7             String str1=strs[i-1];
 8             String str2=strs[i];
 9             int len=Math.min(str1.length(),str2.length());
10             if(len<count){
11                 count=len;
12             }
13             int comNum=0;
14             for(int j=0;j<count;j++){
15                 if(str1.charAt(j)==str2.charAt(j)){
16                     comNum++;
17                 }else{
18                     break;
19                 }
20             }
21             if(comNum<count){
22                 count=comNum;
23             }
24             
25         }
26         if(count==0){
27             return "";
28         }
29         return strs[0].substring(0, count);
30     }

 

【Leetcode-easy】Longest Common Prefix

原文:http://www.cnblogs.com/scecit/p/4981327.html

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