python在字符串中出连续最长的数字串题⽬1:给定⼀个字符串str,输出字符串str中的连续最长的数字串,如果有多个长度相同的串,需全部输出
⽰例 1:
输⼊:s = 'er34y6789jd987634tgvhg'
输出:'987634'
解释:此连续数字串长度最长
⽰例 2:
输⼊:s = '12yu34'
输出:'12','34'
字符串长度怎么数python
解释:有多个连续的,需全部输出
⽰例 3:
输⼊:s = '1yuio'
输出:''
#在字符串中出连续最长的数字串
def findLongestNum(s):
n = len(s)
maxlen = 0
start = 0
res = []
for i in range(n):
if s[i] < '0'or s[i]>'9':
continue
j = i
while j < n:
if s[j] >= '0'and s[j] <= '9':
j += 1
else:
break
tmplen = j-i
if tmplen >= maxlen:
start = i
maxlen = tmplen
res.append(s[start:start+maxlen])
res.sort(key = lambda x: len(x), reverse = True)
l = 0
while l < len(res) and len(res[l])==maxlen:
l += 1
return res[:l]
s = 'eru67yui65tg2vh867g'
print(findLongestNum(s))
View Code

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。