Algorithm

[LeetCode/Python] Longest Common Prefix

YoonSeul 2021. 9. 5. 16:40

문제 설명

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