[14] Longest Common Prefix
https://leetcode.com/problems/longest-common-prefix/description/
- algorithms
- Easy (32.30%)
- Source Code: 14.longest-common-prefix.py
- Total Accepted: 442.6K
- Total Submissions: 1.3M
- Testcase Example: '["flower","flow","flight"]'
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.
python
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ''
return reduce(self.commonOfTwo, strs)
def commonOfTwo(self, s1, s2):
if not s1 or not s2: return ''
len1, len2 = len(s1), len(s2)
ret = ''
for i in range(min(len1, len2)):
if s1[i] == s2[i]:
ret += s1[i]
else:
break
return ret
#
#
# s = Solution()
# print s.longestCommonPrefix([])