Problem:
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: ["flower","flow","flight"]
Output: "FL"
Example 2:
Input: ["dog","racecar","car"]
Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
-Summary-
1. If str list is empty return ""
2. Find a minimum length string in the given strs list input. (Using min() method with a key=len)
3. Enumerate each character in the minimum length string we found, and check if another world contains in it.
4. Return once we found that character does not exist in other words. otherwise, return a full string of minimum length string.
다른 사람이 푼 방법을 보니 zip() method 의 unzip 기능을 이용하여 푼 방법도 있었다.
leetcode.com/problems/longest-common-prefix/discuss/7138/5-line-python-with-zip()-and-len(set())
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]; rtype: str
"""
sz, ret = zip(*strs), ""
# looping corrected based on @StefanPochmann's comment below
for c in sz:
if len(set(c)) > 1: break
ret += c[0]
return ret
https://stackoverflow.com/questions/29139350/difference-between-ziplist-and-ziplist/29139418
https://www.programiz.com/python-programming/methods/built-in/zip
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글
LeetCode. Delete Node in a Linked List [Linked List] (0) | 2020.06.03 |
---|---|
LeetCode. Count and Say [String] (0) | 2020.06.03 |
LeetCode. Implement strStr() [String] (0) | 2020.06.02 |
LeetCode. String to Integer (atoi) [String] (0) | 2020.06.02 |
LeetCode. Valid Palindrome [String] (0) | 2020.06.01 |
댓글