Longest common prefix python

Author: 18th CYL

Date: 2020-10-2

Label: String

Title description

Write a function to find the longest common prefix in a string array.

If there is no common prefix, an empty string "" is returned.

Example

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for input.
Description:

All input contains only lowercase letters az

Problem solving ideas

1. If the character array is empty, return "".
2. Take the first string as the template and judge one character per character

Code

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) <= 0:
            return ""

        sub_str = "" #最长公共子前缀
        temp = ""   

        len_str = len(strs[0])  #记录strs中最短的长度
        for i in strs:
            if len(i) < len_str:
                len_str = len(i)
        
        for i in range(len_str):
            temp = strs[0][i]  #第一个串的第i个字符
            for j in range(len(strs)):
                if strs[j][i] != temp:
                    return sub_str
            sub_str += temp
        return sub_str

Guess you like

Origin blog.csdn.net/cyl_csdn_1/article/details/108904853