码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode第14题 最长公共前缀

时间:2019-01-12 18:30:16      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:时间   comm   元素   code   pen   value   ++   stringbu   val   


/*

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

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

["flower","flow","flight"]
*/


思路1:时间复杂度为O(n*m),遍历数组 ,相同元素放入Stringbuilder中.
  
 1 class Solution14 {
 2 
 3   public String longestCommonPrefix(String[] strs) {
 4     if (strs.length == 1) {
 5       return strs[0];
 6     }
 7     if (strs.length == 0) {
 8       return "";
 9     }
10     int strCount = strs.length;
11     int minLength = Integer.MAX_VALUE;
12 
13     for (String str : strs) {
14       minLength = Math.min(minLength, str.length());
15     }
16 
17     StringBuilder commonPreStr = new StringBuilder();
18 
19     boolean charIsEqual = true;
20     A:
21     for (int j = 0; j < minLength; j++) {
22       for (int i = 1; i < strCount; i++) {
23         charIsEqual = (strs[i].charAt(j) == strs[i - 1].charAt(j));
24         if (!charIsEqual) {
25           break A;
26         }
27       }
28       commonPreStr.append(strs[0].charAt(j));
29     }
30     return commonPreStr.toString();
31   }
32 }

 

思路2: 将第一个字符串视为母串,与剩下的串进行匹配,
如果不匹配(即index返回-1或不为0的情况,不为0说明不是前缀),母串长度-1,直到匹配或母串长度为0为止.

 1 class Solution14 {
 2 
 3   public String longestCommonPrefix(String[] strs) {
 4     if (strs == null || strs.length == 0) {
 5       return "";
 6     }
 7     String result = strs[0];
 8     for (int i = 1; i < strs.length; i++) {
 9       while (strs[i].indexOf(result) != 0) {
10         result = result.substring(0, result.length() - 1);
11       }
12     }
13     return result;
14   }
15 }

 



LeetCode第14题 最长公共前缀

标签:时间   comm   元素   code   pen   value   ++   stringbu   val   

原文地址:https://www.cnblogs.com/rainbow-/p/10260525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!