[알고리즘] leetcode Longost Common Prefix

진실·2022년 11월 24일
0

알고리즘

목록 보기
21/22
post-custom-banner

https://leetcode.com/problems/longest-common-prefix/

from functools import cmp_to_key


class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        def comp(x, y):
            return -1 if len(x) < len(y) else 1

        answer = ""
        strs = sorted(strs, key=cmp_to_key(comp))
        n = len(strs[0])
        i = 0

        while i < n:
            prev = strs[0][i]
            for str in strs:
                if str[i] != prev:
                    return answer
                prev = str[i]
            i += 1
            answer += prev
        return answer

easy문제 답게 EZ했다.

profile
반갑습니다.
post-custom-banner

0개의 댓글