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.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lower-case English letters.
Table of Contents
Solution:
def longestCommonPrefix(self, strs):
prefix=""
if len(strs)==0: return prefix
for i in xrange(len(min(strs))):
c=strs[0][i]
if all(a[i]==c for a in strs):
prefix+=c
else:
break
return prefix
Solution 1:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix=[]
num = len(strs)
for x in zip(*strs):
if len(set(x)) == 1:
prefix.append(x[0])
else:
break
return "".join(prefix) ```
Solution 2:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
if len(strs) == 1: return strs[0]
strs.sort()
p = ""
for x, y in zip(strs[0], strs[-1]):
if x == y: p+=x
else: break
return r
def longestCommonPrefix(self, strs):
prefix=""
if len(strs)==0: return prefix
for i in xrange(len(min(strs))):
c=strs[0][i]
if all(a[i]==c for a in strs):
prefix+=c
else:
break
return prefix
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix=[]
num = len(strs)
for x in zip(*strs):
if len(set(x)) == 1:
prefix.append(x[0])
else:
break
return "".join(prefix) ```
Solution 2:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
if len(strs) == 1: return strs[0]
strs.sort()
p = ""
for x, y in zip(strs[0], strs[-1]):
if x == y: p+=x
else: break
return r
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
if len(strs) == 1: return strs[0]
strs.sort()
p = ""
for x, y in zip(strs[0], strs[-1]):
if x == y: p+=x
else: break
return r