본문 바로가기
💻 LEETCODE

[LEETCODE] 14. Longest Common Prefix

by 구라미 2022. 11. 22.

 

 

 

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

 

베리 파이써닉 하다는 찬사를 받은 코드...

 

 

 

 

 

댓글