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