Skip to content

Commit 36ed7d3

Browse files
author
weiy
committed
longest common prefix easy
1 parent 14c0e56 commit 36ed7d3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

String/LongestCommonPrefix.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Write a function to find the longest common prefix string amongst an array of strings.
3+
4+
If there is no common prefix, return an empty string "".
5+
6+
Example 1:
7+
8+
Input: ["flower","flow","flight"]
9+
Output: "fl"
10+
Example 2:
11+
12+
Input: ["dog","racecar","car"]
13+
Output: ""
14+
Explanation: There is no common prefix among the input strings.
15+
Note:
16+
17+
All given inputs are in lowercase letters a-z.
18+
19+
20+
21+
所有单词的共同的前缀。
22+
没什么技巧,从每个单词的第一个开始对比就好了。
23+
Python 中有一个 zip 可以做这些事情。
24+
25+
beat 90%
26+
27+
测试地址:
28+
https://leetcode.com/problems/longest-common-prefix/description/
29+
30+
今日的零启动任务。
31+
32+
"""
33+
class Solution(object):
34+
def longestCommonPrefix(self, strs):
35+
"""
36+
:type strs: List[str]
37+
:rtype: str
38+
"""
39+
result = ""
40+
41+
for i in zip(*strs):
42+
a = i[0]
43+
for j in i[1:]:
44+
if j != a:
45+
return result
46+
else:
47+
result += a
48+
49+
return result
50+

0 commit comments

Comments
 (0)