首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >回文复现

回文复现
EN

Stack Overflow用户
提问于 2014-04-13 21:48:00
回答 1查看 92关注 0票数 0

根据docstring,我正在尝试做一个稍微高级一些的回文。但是我不能让它起作用。我走的路对不对?到目前为止,这就是我所拥有的:

代码语言:javascript
运行
复制
def pal_length(s: str, n: int) -> bool:


'''Return True iff s has a palindrome of length exactly n.

  >>> pal_length('abclevel', 5)
  True
  >>> pal_length('level', 2)
  False
  '''
  if not s:
      return True
  else:
      index = 0
      while index < len(s):
          if s[index] == s[index+n]:
              return pal_length(s[index+1:index+n-1],n-1)
          index += 1
  return False

我试图不使用任何导入模块等,只是直接递归。

任何帮助都是非常感谢的。谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-13 21:58:47

我觉得你的索引有点离谱。不是应该吗

代码语言:javascript
运行
复制
index = 0
while index < len(s) - n + 1:
    if s[index] == s[index+n-1]:
        return pal_length(s[index+1:index+n-1], n-2)
    index += 1
return False
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23048831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档