Leetcode# [14] Longest Common Prefix

One novel solution to the easy problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

It works because the sort function will sort the strings by prefix. So if the last string has the same prefix with the first string, it means that all the string within the range would satisfy the property of common prefix.

0%