1. 程式人生 > >LeetCode第14題 最長公共前綴

LeetCode第14題 最長公共前綴

mon efi char 字符串 不存在 bool 第一個 for pan


/*

編寫一個函數來查找字符串數組中的最長公共前綴。

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

["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題 最長公共前綴