[LeetCode] 14.Longest Common Prefix (Python)

2025. 1. 15. 11:26·코딩 테스트
728x90

1.문제

https://leetcode.com/problems/longest-common-prefix/?envType=study-plan-v2&envId=top-interview-150

2.풀이

1) 주어진 리스트의 원소를 길이순으로 정렬한다.

2) 가장 짧은 단어를 기준으로 순환하여 비교한다.

3) 반복문을 돌면서 해당 index 의 단어와 첫번째 단어의 index 가 동일한지 체크하고 동일하지 않다면 그 부분까지 substring 해서 반환한다.

 

3.코드

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
  
        if (len(strs) == 0):
            return ""
  
        if (len(strs) == 1):
            return strs[0]

        strs.sort(key=len)
        if (strs[0] == ""):
            return ""

        #no common prefix
        if (strs[0][0] != strs[1][0]):
            return ""

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

        return strs[0]
728x90
저작자표시 비영리 변경금지 (새창열림)

'코딩 테스트' 카테고리의 다른 글

[LeetCode] RansomNote (Python)  (0) 2025.01.15
[LeetCode] Find the Index of the First Occurrence in a String (Python)  (0) 2025.01.15
[LeetCode] Length of Last Word (Python)  (0) 2025.01.15
[LeetCode] Roman to Integer  (0) 2025.01.14
[LeetCode] In Subsequence (Python)  (0) 2025.01.13
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] RansomNote (Python)
  • [LeetCode] Find the Index of the First Occurrence in a String (Python)
  • [LeetCode] Length of Last Word (Python)
  • [LeetCode] Roman to Integer
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바
    이분탐색
    자료구조
    금융용어
    스프링
    코테공부
    Python
    코딩테스트
    스프링부트
    Kotlin
    리트코드
    코딜리티
    알고리즘
    kafka
    코딩
    LeetCode
    springboot
    db
    Spring
    카카오코테
    쿠버네티스
    코테
    pythoncodingtest
    java
    codility
    프로그래머스
    MySQL
    CodingTest
    네트워크
    C++
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] 14.Longest Common Prefix (Python)
상단으로

티스토리툴바