Change the Better World

Longest Common Prefix 본문

Programming/Python

Longest Common Prefix

white_cheetah 2022. 6. 9. 21:49

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.
class Solution(object):
    def longestCommonPrefix(self, strs):
       
        result = ""
        strs = sorted(strs)
        for i in range(len(strs[0])):
            s = strs[0][i]  #frist alphabet
            for j in strs:
                flag = False
                if s == j[i]:
                    flag = True
                else:
                    flag = False
           
            if flag == True:
                result += s
            else:
                break
       
        return result
Runtime: 33 ms, faster than 41.26% of Python online submissions for Longest Common Prefix.
Memory Usage: 13.9 MB, less than 12.93% of Python online submissions for Longest Common Prefix.
Comments