Problem
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.
Note:
All given inputs are in lowercase letters a-z
.
Solution: Brute Force
Time complexity: O(mk), where k the length of common prefix.
Space complexity: O(k)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) return ""; string ans; for (int i = 0; i < strs[0].size(); ++i) { for (const string& s : strs) if (s.length() <= i || s[i] != strs[0][i]) return ans; ans += strs[0][i]; } return ans; } }; |
Java
Time complexity: (mk + k^2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Author: Huahua class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; String ans = new String(); for (int i = 0; i < strs[0].length(); ++i) { char c = strs[0].charAt(i); for (String s : strs) if (s.length() <= i || s.charAt(i) != c) return ans; ans += c; } return ans; } } |
Python3
1 2 3 4 5 6 7 8 9 10 |
# Author: Huahua class Solution: def longestCommonPrefix(self, strs): if not strs: return "" ans = "" for i in range(len(strs[0])): for s in strs: if len(s) <= i or s[i] != strs[0][i]: return ans ans += strs[0][i] return ans |