본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode. Longest Common Prefix [String]

by 벤진[Benzene] 2020. 6. 2.

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

 

Difference between zip(list) and zip(*list)

I am using a list p = [[1,2,3],[4,5,6]] If I do : >>>d=zip(p) >>>list(d) [([1, 2, 3],), ([4, 5, 6],)] Though, what I actually want is obtained using this: >>>d=zip(*p...

stackoverflow.com

https://www.programiz.com/python-programming/methods/built-in/zip

 

Python zip()

The syntax of the zip() function is: zip(*iterables) zip() Parameters Parameter Description iterables can be built-in iterables (like: list, string, dict), or user-defined iterables Recommended Reading: Python Iterators, __iter__ and __next__ Return Value

www.programiz.com

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글