[Leetcode]14. Longest Common Prefix

김지원·2022년 3월 24일
0
post-custom-banner

📄 Description

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

Example 1:

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

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

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

💻 My Submission

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        answer=''
        # index of the string, start with 0
        i=0
        len_list=[len(s) for s in strs]
        min_len=min(len_list)

        while i<min_len:
            check_list=[s[i] for s in strs]
            if len(set(check_list))==1: i+=1
            else: break

        return strs[0][:i]

What I learned

  1. How to use min() funtion in pythonic way

💡 min() function Syntax

min(iterable, *iterables, key, default)

  • My code
    len_list=[len(s) for s in strs]
    min_len=min(len_list)
  • Better code
    shortest = min(strs,key=len)

References
https://leetcode.com/problems/longest-common-prefix/

profile
Make your lives Extraordinary!
post-custom-banner

0개의 댓글