Skip to content

Commit cf6ef72

Browse files
committed
strings: add longest_common_prefix algorithm with doctests
1 parent 788d95b commit cf6ef72

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

strings/longest_common_prefix.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def longest_common_prefix(strs: list[str])->str:
2+
"""
3+
:type strs: List[str]
4+
5+
Args:
6+
strs (list[str]): A list of strings.
7+
8+
9+
Returns:
10+
str:The longest common prefix shared among all strings.
11+
Returns an empty string if there is none.
12+
13+
Test cases:
14+
>>> longest_common_prefix(["flower","flow","flap"])
15+
'fl'
16+
>>> longest_common_prefix(["cats","dragon","dracula"])
17+
''
18+
>>> longest_common_prefix(["marianne","mariachi"])
19+
'maria'
20+
>>> longest_common_prefix([])
21+
''
22+
>>> longest_common_prefix(["","belly","belt"])
23+
''
24+
>>> longest_common_prefix(["#hashtag","#hashbrown","#hash"])
25+
'#hash'
26+
"""
27+
ans=""
28+
if not strs:
29+
return ""
30+
if len(strs)==1:
31+
return strs[0]
32+
33+
k=0
34+
ref=strs[0]
35+
36+
while k<len(ref):
37+
for ele in strs:
38+
if len(ele)<k+1 or ref[k]!=ele[k]:
39+
40+
return ans
41+
ans+=ele[k]
42+
k+=1
43+
return ans
44+
45+
46+
47+
48+

0 commit comments

Comments
 (0)