14. 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: ["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
.
---
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String longestCommonPrefix(String[] strs) { | |
Arrays.sort(strs); | |
String first = strs[0], last = strs[strs.length - 1]; | |
int i = 0, minLength = Math.min(first.length(), last.length()); | |
while (i < minLength) { | |
if (first.charAt(i) != last.charAt(i)) { | |
break; | |
} | |
i++; | |
} | |
return first.substring(0, i); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def longestCommonPrefix(self, strs): | |
""" | |
:type strs: List[str] | |
:rtype: str | |
""" | |
strs = sorted(strs) | |
i = 0 | |
while i < min(len(strs[0]), len(strs[-1])): | |
if strs[0][i] != strs[-1][i]: | |
return strs[0][0:i] | |
i += 1 | |
return strs[0][0:i] |