Longest Common Prefix

Minsu Kang·2025년 1월 24일

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

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 if it is non-empty.

내 코드

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        prefix = ""

        for i in range(len(strs[0])):
            for j in strs:
                if strs[0][i] != j[i]:
                    return prefix
            prefix += strs[0][i]
        return prefix

런타임 에러가 났음.

Leet Code

class Solution(object):
    def longestCommonPrefix(self, strs):
        pref = ''
        for i in range(len(strs[0])):
            for j in strs:
                if i>=len(j) or j[i]!=strs[0][i]:
                    return pref
            pref+=strs[0][i]
        return pref

여기서 생각해볼 점은 왜 i < len(j)의 조건을 넣었냐임.
이 포인트가 IndexError: string index out of range
if strs[0][i] != j[i]:
에러를 방지함. 그래서 i가 j component의 길이보다 길면 없애야함.

profile
안녕하세요! 강민수입니다.

0개의 댓글