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

如何让回文字符串检测忽略空格?需修改给定代码完成作业

如何修改回文检测代码以忽略空格?

要让这段回文检测代码忽略空格,有两种直观的实现方式,下面分别说明:

方法一:预处理字符串,过滤空格

最直接的方式是在将字符加入双端队列前,先跳过所有空格。这样队列里只会保留需要参与比较的非空格字符,后续的逻辑不需要改动。

修改后的完整代码:

def palchecker(aString):
    chardeque = Deque()

    for ch in aString:
        if ch != ' ':  # 仅把非空格字符加入队列
            chardeque.addRear(ch)
        

    stillEqual = True

    while chardeque.size() > 1 and stillEqual:
        first = chardeque.removeFront()
        last = chardeque.removeRear()
        if first != last:
            stillEqual = False

    return stillEqual

print(palchecker("lsdkjfskf"))  # 输出 False
print(palchecker("radar"))      # 输出 True
print(palchecker("a man a plan a canal panama"))  # 输出 True

方法二:在比较阶段跳过空格

如果需要保留原字符串的字符结构(比如后续可能有其他处理需求),可以在取出队列首尾字符时,跳过空格再进行比较。这种方式需要调整循环内的逻辑:

修改后的完整代码:

def palchecker(aString):
    chardeque = Deque()

    for ch in aString:
        chardeque.addRear(ch)
        

    stillEqual = True

    while chardeque.size() > 1 and stillEqual:
        first = chardeque.removeFront()
        # 跳过前端的空格
        while first == ' ' and chardeque.size() > 0:
            first = chardeque.removeFront()
        
        last = chardeque.removeRear()
        # 跳过后端的空格
        while last == ' ' and chardeque.size() > 0:
            last = chardeque.removeRear()
        
        # 处理队列只剩一个空格的边界情况
        if first == ' ' or last == ' ':
            continue
        
        if first != last:
            stillEqual = False

    return stillEqual

print(palchecker("lsdkjfskf"))  # 输出 False
print(palchecker("radar"))      # 输出 True
print(palchecker("a man a plan a canal panama"))  # 输出 True

两种方法中,方法一的代码更简洁高效,因为提前过滤了不需要的空格,减少了后续的比较次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:46:16