Finding The Longest Substring Of Repeating Characters In A String
Solution 1:
Your program will fail on:
40011
It will return just 11
.
The problem is that the length of str(int('00'))
is equal to 1.
You could fix it by removing the int
and str
calls from your program (i.e. saving the answers as strings instead of ints).
Solution 2:
Peter de Rivaz seems to have identified the problem with your code, however, if you are interested in a different way to solve this problem consider using a regular expression.
import sys
import re
next(sys.stdin) # length not needed in Python
s = next(sys.stdin)
repeats = r'(.)\1+'for match in re.finditer(repeats, s):
print(match.group())
The pattern (.)\1+
will find all substrings of repeated digits. Output for input
10 3445556788
would be:
44 555 88
If re.finditer()
finds that there are no repeating digits then either the string is empty, or it consists of a sequence of increasing non-repeating digits. The first case is excluded since n must be greater than 0. For the second case the input is already sorted alphabetically, so just output the length and each digit.
Putting it together gives this code:
import sys
import re
next(sys.stdin) # length not needed in Python
s = next(sys.stdin).strip()
repeats = r'(.)\1+'
passwords = sorted((m.group() for m in re.finditer(repeats, s)),
key=len, reverse=True)
passwords = [s for s in passwords iflen(s) == len(passwords[0])]
iflen(passwords) == 0:
passwords = list(s)
print(len(passwords))
print(*passwords, sep='\n')
Note that the matching substrings are extracted from the match
object and then sorted by length descending. The code relies on the fact that digits in the input must not decrease so a second alphabetic sort of the candidate passwords is not required.
Post a Comment for "Finding The Longest Substring Of Repeating Characters In A String"