題目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))
