Zero to Hero
Published 2021. 4. 20. 16:42
14. Longest Common Prefix Algorithm
 

Longest Common Prefix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. 완전 탐색

from typing import *


class Solution:
    def sol(self, strs, length):
        if length == 0:
            return True
        for strr in strs:
            # length 보다 문자열이 짧은 상황은 불가능하니깐 반환
            if len(strr) < length:
                return False
            if strs[0][:length] != strr[:length]:
                return False
        else:
            return True

    def longestCommonPrefix(self, strs: List[str]) -> str:
        # 빈 list가 오면 반환
        if not strs:
            return ""
        # list에 문자열이 하나만 있으면 반환
        if len(strs) == 1:
            return strs[0]
        answer_length = 0
        while True:
            if not self.sol(strs, answer_length):
                break
            answer_length += 1
        return strs[0][:answer_length - 1]

2. (내가 생각하는 정해) 이진 탐색

추후 기술

'Algorithm' 카테고리의 다른 글

136. Single Number  (0) 2021.04.22
617. Merge Two Binary Trees  (0) 2021.04.21
424. Longest Repeating Character Replacement  (0) 2021.04.19
2174번: 로봇 시뮬레이션  (0) 2021.04.18
7. Reverse Integer  (0) 2021.04.17
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!