File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments