공대생의 비망록

[LeetCode][Easy] Longest Common Prefix 문제 Python 풀이 본문

Programming Language/Python

[LeetCode][Easy] Longest Common Prefix 문제 Python 풀이

myungsup1250 2026. 2. 9. 18:06

주어진 문자열 배열 strs에 대하여, 가장 긴 공통문자열을 찾는 문제.

예를 들어 "flower", "flow", "flight" 문자열들이 주어졌다면 "fl"을 찾아 반환해야 한다.

 

문제 풀이:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        length = 201 # Since the max length for this problem is 200.
        # length = min(len(w) for w in strs) # Pythonic way
        for s in strs: # set var length as the shortest string's length.
            if length > len(s):
                length = len(s)

        common = ""
        for i in range(length):
            tmp = strs[0][i]; add = True
            for s in strs:
                if tmp != s[i]:
                    return common
            common += tmp
        return common
Comments