python删除字符串中重复字符_python-查找字符串中重复字符的最长子字符串

本文讨论了一道编程挑战,涉及到寻找一个非递减数字字符串中的最长回文子串作为火星数据库的密码。作者提出了一些观察和解决方案,但遇到了问题。关键点包括回文字符串定义、重复字符长度计算以及过滤出最长密码。然而,代码在处理某些情况时出错,特别是在处理前导零时。解决方案是去除将结果转换为整数和字符串的步骤。
摘要由CSDN通过智能技术生成

除非我真的真的被卡住,否则我会尽量不寻求有关代码强制问题的帮助,而这恰好是现在.

Your first mission is to find the password of the Martian database. To achieve this, your best secret agents have already discovered the following facts:

The password is a substring of a given string composed of a sequence of non-decreasing digits

The password is as long as possible

The password is always a palindrome

A palindrome is a string that reads the same backwards. racecar, bob, and noon are famous examples.

Given those facts, can you find all possible passwords of the database?

Input

The first line contains n, the length of the input string (1 ≤ n ≤ 105).

The next line contains a string of length n. Every character of this string is a digit.

The digits in the string are in non-decreasing order.

Output

On the first line, print the number of possible passwords, k.

On the next k lines, print the possible passwords in alphabetical order.

我的观察是:

>非递减字符串中的回文仅是重复字符的字符串(例如“ 4444”或“ 11”)

>在字符i上,i的最后一个实例-i 1的第一个实例=重复字符的长度

>跟踪最大密码长度,然后过滤出所有比最大密码长度短的项目,以确保输出的密码为最大长度

基于这些观察,我的解决方案是:

n,s = [input() for i in range(2)]#input

maxlength = 0

results = []

for i in s:

length = (s.rfind(i)-s.find(i))+1

if int(i*(length)) not in results and length>=maxlength:

results.append(int(i*(length)))

maxlength = length

#filer everything lower than the max password length out

results = [i for i in results if len(str(i))>=maxlength]

#output

print(len(results))

for y in results:

print(y)

不幸的是,该解决方案实际上是错误的,并且在第4个测试用例上失败.我不了解代码有什么问题,因此无法修复.有人可以帮忙吗?

谢谢阅读!

解决方法:

您的程序将失败:

4

0011

它只会返回11.

问题在于str(int(’00’))的长度等于1.

您可以通过从程序中删除int和str调用来解决此问题(即将答案另存为字符串而不是int).

标签:python,string,algorithm

来源: https://codeday.me/bug/20191011/1896265.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值