对于像'12233322155552'
这样的字符串,通过删除重复项,我可以得到'1235'
。
但我想保留的是'1232152'
,只删除连续的重复项。
发布于 2012-07-16 14:01:59
import re
# Only repeated numbers
answer = re.sub(r'(\d)\1+', r'\1', '12233322155552')
# Any repeated character
answer = re.sub(r'(.)\1+', r'\1', '12233322155552')
发布于 2017-05-24 19:57:45
你可以使用itertools
,这是一个内联代码
>>> s = '12233322155552'
>>> ''.join(i for i, _ in itertools.groupby(s))
'1232152'
发布于 2012-07-13 05:22:56
微软/亚马逊求职面试类型的问题:这是伪代码,实际代码留作练习。
for each char in the string do:
if the current char is equal to the next char:
delete next char
else
continue
return string
作为更高层次的尝试(而不是实际的实现):
for s in string:
if s == s+1: ## check until the end of the string
delete s+1
https://stackoverflow.com/questions/11460855
复制相似问题