Longest Common Prefix
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: strs = ["flower","flow","flight"] Output: "fl"
Example 2: Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
[ "[\"flower\",\"flow\",\"flight\"]" ]
Explanation. The longest common prefix among "flower", "flow", and "flight" is "fl".
[ "[\"dog\",\"racecar\",\"car\"]" ]
Explanation. There is no common prefix among "dog", "racecar", and "car".
[ "[\"apple\",\"apple\",\"apple\"]" ]
Explanation. All strings are identical, so the entire string "apple" is the common prefix.
[ "[\"apple\",\"apricot\",\"apply\"]" ]
Explanation. The longest common prefix among "apple", "apricot", and "apply" is "ap".
[ "[\"\",\"b\"]" ]
Explanation. If one of the strings is empty, the common prefix must be empty.
[ "[\"a\"]" ]
Explanation. With only one string, that string itself is the longest common prefix.
[ "[\"aa\",\"a\"]" ]
Explanation. The shorter string 'a' is a prefix of 'aa'.
Follow-up: Can you optimize your solution to handle cases where the input array `strs` is extremely large but the strings themselves are relatively short? Consider a Trie-based approach or a divide and conquer strategy.
1. `1 <= strs.length <= 200` 2. `0 <= strs[i].length <= 200` 3. `strs[i]` consists of only lowercase English letters.
- Views
- 2