Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
這題有好幾種解法,個人認為會1,2的解法就可以了,但這種多方法解題的思路可以好好學習一下。具體可參考:Longest Common Prefix
1. 一個一個字符串取比較word by word matching:
先拿前2個,從第一位開始比較,直到發現有不同的字符,此時前面一樣的字符串在去和后面的字符串比較,直到結束。可以用遞歸。
Time: O(n*m) (n是字符串個數,m是字符串最長長度) Space: O(m)
2. 一個字符一個字符的比較character by character matching:
所有的字符串同時比較第1個,第2個.......,發現有不同的出現,之前一樣的就是找到的最長共同前綴。Time: O(n*m) (n是字符串個數,m是字符串最長長度) Space: O(m)
3. divide and conquer:
把所有字符串分成兩組,分別去比較,最后都剩一個的時候,兩組在比較。Time: O(n*m), Space: O(n*logm)
4. 二分法Binary Search:
先找到最短的字符串,然后把這個最短的字符串二分成前面和后面兩部分,前面的和所有剩下字符串比較,如果一樣在比較后面的,如果有不一樣的,則后面的部分不用比較了,前面的部分在二分比較。Time: O(n*m*logm), Space: O(m)
5. 使用Trie:
首先了解Trie數據結構,然后把所有的字符串都執行一遍插入到Trie,然后讀取Trie中最后一個沒有分支的node,此時之前這些字符就是答案。
Time: O(n*m + m), Space: O(26*m*n) ~ O(m*n)
Java: Method 1
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } String prefix = strs[0]; for(int i = 1; i < strs.length; i++) { int j = 0; while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) { j++; } if( j == 0) { return ""; } prefix = prefix.substring(0, j); } return prefix; } }
Java: Method 2
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; String res = new String(); for (int j = 0; j < strs[0].length(); ++j) { char c = strs[0].charAt(j); for (int i = 1; i < strs.length; ++i) { if (j >= strs[i].length() || strs[i].charAt(j) != c) { return res; } } res += Character.toString(c); } return res; } }
Java: Method 2
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; for (int j = 0; j < strs[0].length(); ++j) { for (int i = 0; i < strs.length - 1; ++i) { if (j >= strs[i].length() || j >= strs[i + 1].length() || strs[i].charAt(j) != strs[i + 1].charAt(j)) { return strs[i].substring(0, j); } } } return strs[0]; } }
Python: Method 2
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" for i in xrange(len(strs[0])): for string in strs[1:]: if i >= len(string) or string[i] != strs[0][i]: return strs[0][:i] return strs[0]
C++: Method 2
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.size() == 0) { return ""; } string prefix = ""; for (int i = 0; i < strs[0].length(); i++) { for (int j = 1; j < strs.size(); j++) { if (strs[j][i] != strs[0][i]) { return prefix; } } prefix += strs[0][i]; } return prefix; } };
All LeetCode Questions List 題目匯總