python 在字符串中找出连续最长的数字串
题目1:给定一个字符串str,输出字符串str中的连续最长的数字串,如果有多个长度相同的串,需全部输出
示例 1:
输入:s = 'er34y6789jd987634tgvhg'
输出:'987634'
解释:此连续数字串长度最长
示例 2:
输入:s = '12yu34'
输出:'12','34'
解释:有多个连续的,需全部输出
示例 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))