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 "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters.
내 풀이
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
result = ''
first = strs[0]
if len(strs) == 1:
return first
if (first == ""):
return result
for idx, char in enumerate(first):
test = list(map(lambda x: len(x) > idx and x[idx] and x[idx] == char, strs))
if (all(test)):
result += char
if len(first) -1 == idx:
return result
else:
return result
다른 풀이
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortest = min(strs,key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest
베리 파이써닉 하다는 찬사를 받은 코드...
'💻 LEETCODE' 카테고리의 다른 글
[LEETCODE] 1991. Find the Middle Index in Array (0) | 2022.11.24 |
---|---|
[LEETCODE] 20. Valid Parentheses (0) | 2022.11.23 |
[LEETCODE] 9. Palindrome Number (0) | 2022.11.22 |
[LEETCODE] 383. Ransom Note (0) | 2022.11.22 |
[LEETCODE] 876. Middle of The Linked List (0) | 2022.11.22 |
댓글