You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode最长公共前缀问题代码调试求助:新手实现逻辑错误排查

Troubleshooting My Longest Common Prefix Code (LeetCode)

Problem Background

This is the Longest Common Prefix problem from LeetCode. The task is to write a function that finds the longest common prefix string among an array of strings. If there's no common prefix, return an empty string "".

Example:

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

My Situation & Issue

I'm new to programming and tried solving this problem. My approach was to first find the shortest string in the array, then verify the common prefix step by step based on this string. But my code isn't working as expected: when I test the example above, it outputs "flo" instead of "fl", and I noticed the while loop doesn't seem to run properly at all. I'd really appreciate help figuring out where I went wrong.

My Code

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        string = ""
        len_st = []
        for st in strs:
            len_st.append(len(st))
        m = min(len_st)
        prefix = strs[len_st.index(m)]
        while prefix:
            for st in strs:
                if prefix in st:
                    continue
                else:
                    prefix = prefix.replace(prefix[-1], "")
                    break
            return prefix
        else:
            return ""

Let's break down the issues in your code one by one, then fix them:

1. Wrong Check: Substring vs. Prefix

The condition if prefix in st checks if prefix is any substring of st, not if it's the starting prefix. For example, if you had a string like "xxflowxx", "flow" would be a substring but not a prefix—this logic would incorrectly mark it as a match. We need to check if the string starts with the prefix specifically.

2. Early Return Kills the While Loop

Your return prefix statement is placed right after the inner for loop, inside the while block. That means after the first iteration of checking strings (even if you trimmed the prefix once), you immediately return the result. The while loop never gets a chance to run again to keep trimming the prefix until it works for all strings.

3. Unsafe Prefix Trimming

Using prefix.replace(prefix[-1], "") is risky. If the last character appears multiple times in the prefix, this will replace all instances of it, not just the last one. For example, if prefix was "ffl", this would turn it into an empty string instead of "ff". The safe way to remove just the last character is prefix = prefix[:-1].

Fixed Code

Here's the corrected version that addresses all these issues:

from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        
        # Find the shortest string to use as initial prefix
        len_st = [len(st) for st in strs]
        shortest_len = min(len_st)
        prefix = strs[len_st.index(shortest_len)]
        
        while prefix:
            # Check if current prefix is a valid start for ALL strings
            all_match = True
            for st in strs:
                if not st.startswith(prefix):
                    all_match = False
                    break
            if all_match:
                return prefix
            # Trim the last character and try again
            prefix = prefix[:-1]
        
        # If we've trimmed down to empty string
        return ""

Key Fixes Explained:

  • Replaced prefix in st with st.startswith(prefix) to correctly check for prefixes.
  • Moved the return statement to only trigger when the prefix matches all strings—otherwise, we trim the prefix and loop again.
  • Used prefix[:-1] to safely remove just the last character of the prefix.
  • Added a check for empty input arrays to handle edge cases gracefully.

Testing this with your example ["flower","flow","flight"]:

  1. Initial prefix is "flow" (the shortest string).
  2. Check if all strings start with "flow"—"flight" doesn't, so trim to "flo".
  3. Check again—"flight" still doesn't start with "flo", trim to "fl".
  4. Check again—all strings start with "fl", so return "fl" as expected.

内容的提问来源于stack exchange,提问作者lulia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:42:39