data-sree / Python_codes

0 stars 0 forks source link

Longest_Common_Prefix.py #2

Open Nirmal1901 opened 5 months ago

Nirmal1901 commented 5 months ago

About the code: The provided code is a Python implementation of the longest common prefix problem. It takes in a list of strings as input and returns the longest common prefix among them.

Status: Good

Issues: None

Improved code:

class Solution(object):
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""
        min_str = min(strs)
        max_str = max(strs)
        for index, char in enumerate(min_str):
            if char != max_str[index]:
                return min_str[:index]
        return min_str

Explanation: The improved code is a more concise and efficient version of the original code. It uses the built-in min() and max() functions to find the shortest and longest strings in the input list, respectively. Then, it compares each character of the shortest string with the corresponding character of the longest string, and returns the longest common prefix if there is any difference. If there is no difference, it returns the entire shortest string.

Overall, this code is well-structured and easy to understand. The use of built-in functions like min() and max() makes the code more concise and efficient.

data-sree commented 5 months ago

Thanks for the suggestions