longest common prefix leetcode
#604
- Author
- socdev
- Created
- Dec. 3, 2022, 8:42 p.m.
- Expires
- Never
- Size
- 834 bytes
- Hits
- 54
- Syntax
- Python
- Private
- ✗ No
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# https://leetcode.com/problems/longest-common-prefix/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
all = []
for s in strs:
for i in range(len(s)):
all.append(s[0:(len(s)-i)])
d = {}
for x in all:
if x in d:
d[x] = d[x] + 1
else:
d[x] = 1
longest = ""
for key in d.keys():
if d[key] == len(strs):
longest = key if len(longest) < len(key) else longest
return longest