DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

4 2

LeetCode "Longest Common Prefix"

Oh😮 I didn't know that question number is not fixed😧

Longest Common Prefix

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return ''

        # check what is needed length
        min_len = len(strs[0])
        other_strs = strs[1:]
        for s in other_strs:
            len_s = len(s)
            if min_len > len_s:
                min_len = len_s

        # check prefix
        c = ''
        prefix = ''
        for i in range(min_len):
            c = strs[0][i]
            for s in other_strs:
                if c != s[i]:
                    c = ''

            # not longer a prefix
            if not c:
                break

            prefix += c

        return prefix
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay