Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 48a87a6

Browse files
committed
Create longest_common_prefix.py
1 parent 62490bc commit 48a87a6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎arrays_hashing/longest_common_prefix.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# You are given an array of strings strs. Return the longest common prefix of all the strings.
2+
# If there is no longest common prefix, return an empty string "".
3+
# Example 1:
4+
# Input: strs = ["bat","bag","bank","band"]
5+
# Output: "ba"
6+
# Example 2:
7+
# Input: strs = ["dance","dag","danger","damage"]
8+
# Output: "da"
9+
# Example 3:
10+
# Input: strs = ["dog","racecar","car"]
11+
# Output: ""
12+
# Explanation: There is no common prefix among the input strings.
13+
14+
from typing import List
15+
16+
class Solution1:
17+
def longestCommonPrefix(self, strs: List[str]) -> str:
18+
19+
longest_common_prefix = ""
20+
21+
sorted_list = sorted(strs)
22+
23+
first = sorted_list[0]
24+
last = sorted_list[-1]
25+
26+
for i in range(min(len(first), len(last))):
27+
if first[i] == last[i]:
28+
longest_common_prefix += first[i]
29+
else:
30+
break
31+
return longest_common_prefix
32+
33+
print(Solution1().longestCommonPrefix(["bat","bag","bank","band"]))
34+
print(Solution1().longestCommonPrefix(["dance","dag","danger","damage"]))
35+
print(Solution1().longestCommonPrefix(["dog","racecar","car"]))
36+
37+
class Solution2:
38+
39+
def longestCommonPrefix(self, strs: List[str]) -> str:
40+
41+
base = strs[0]
42+
43+
for i in range(len(base)):
44+
for s in strs[1:]:
45+
if i == len(s) or s[i] != base[i]:
46+
return base[0:i]
47+
48+
return base
49+
50+
print(Solution2().longestCommonPrefix(["bat","bag","bank","band"]))
51+
print(Solution2().longestCommonPrefix(["dance","dag","danger","damage"]))
52+
print(Solution2().longestCommonPrefix(["dog","racecar","car"]))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /