Skip to content

Latest commit

 

History

History
50 lines (38 loc) · 1.56 KB

풀이_LC14.md

File metadata and controls

50 lines (38 loc) · 1.56 KB

🧡 LeetCode 14. Longest Common Prefix

  • Date : 2021.07.11(일)
  • Time : 25분

Problem

  • 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 "".

Constraints

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

Example

  • Input: strs = ["flower","flow","flight"]
  • Output: "fl"



풀이

     def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 1:
            return strs[0]
        else:
            max_string = ''
            root = strs[0]
            
            i, counter = 1, 1
            
            while i <= len(root):
                if root[:i] == strs[counter][:i]:
                    if counter < len(strs) - 1:
                        counter += 1
                        continue
                    else:
                        max_string = root[:i]
                        i += 1
                        counter = 1
                        continue
                else:
                    break
        return max_string

: 문자열을 배열로 받아, 중복되는 문자 중 제일 긴 문자를 찾아내는 문제였다. 그렇기 때문에 배열이 1개밖에 들어오지 않았다면, 그 문자 자체가 정답이므로 먼저 예외처리를 진행해주었다. 이제 그런 예외 상황이 아니라면, 배열의 첫번째 값을 기준으로 잡고, 그 다음 배열 문자열과 비교해가면서 중복된 문자열을 찾는다.