본문 바로가기

Algorithm

[LeetCode/Python] 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 "".

 

예시

제한

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.

 

 

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

 

풀이

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        answer = ""
        for i in range(min([len(i) for i in strs])):
            val = 0
            for j in range(len(strs)):
                if j == len(strs)-1:
                    break
                if strs[j][i] != strs[j+1][i]:
                    val = 1
                    break
            if val == 0:
                answer+= strs[0][i]
            else:
                break
        return answer

'Algorithm' 카테고리의 다른 글

[백준/Python] ATM  (0) 2021.09.28
[LeetCode/Python] Valid Parentheses  (0) 2021.09.05
[LeetCode/Python] Roman to Integer  (0) 2021.09.05
[LeetCode/Python] Reverse Integer  (0) 2021.09.05
[프로그래머스 Level2] 소수 찾기  (0) 2021.09.04