Write a function to find the longest common prefix string amongst an array of strings.
我的解法
這題easy題我提交了N次才過,數(shù)組下標(biāo)老是outofrange。后來我還是先用一趟遍歷把數(shù)組最短字符串的長度求出來,再挨個判斷subString了。復(fù)雜度O(S) ,S是所有字符串的長度之和。
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
if (strs.length == 1) return strs[0];
int minLen = Integer.MAX_VALUE;
for (String s : strs) {
minLen = Math.min(s.length(), minLen);
}
if (minLen == 0) return "";
int end = 1;
for (; end <= minLen; end++) {
for (String s : strs) {
String temp = strs[0].substring(0, end);
if (!s.substring(0, end).equals(temp))
return strs[0].substring(0, end - 1);
}
}
return strs[0].substring(0, end-1);
}
這個寫法類似下面的solutions2。但是不需要先遍歷一次找最短長度的。
Solution里的解法:
Approach #1 (Horizontal scanning)
第一種,水平搜索,寫得真是巧妙啊,先找出前兩個string的最長subprefix(拿strs[0]作為prefix),再依次拿這個prefix跟后面的string比,不斷extract。Time是O(S),因為indexOf也是用了O(n)的時間遍歷。
Approach #2 (Vertical scanning)
上一種的缺陷是如果這個strs[]里最后一個元素是""這樣非常短的元素,那前面的比較就白做了。那么就if (i == strs[j].length() || strs[j].charAt(i) != c)來依次比對每個str的第i個字符。這個寫法讓我想到我上面的寫法,是不需要先求出最短長度的,就用第一個的長度來iterate,遇到不滿足的直接return就行了。
Approach #3 (Divide and conquer)
divide and conque也是把我看呆了。。遞歸。后悔研一算法沒認真學(xué)王海艷的算法課,好想回去再學(xué)一遍。。做了100多題真的沒用過分治。
Approach #4 (Binary search)
二分查找也把我看呆了。
Further Thoughts / Follow up
Follow up 也把我看呆了。給一個string q和一個string數(shù)組,求它們的LCP。竟然用到了Trie。確實是可以把數(shù)組里的這些string用trie來表示的。
( https://leetcode.com/articles/implement-trie-prefix-tree/)