首页 > 试题广场 >

在字符串中找出连续最长的数字串

[编程题]在字符串中找出连续最长的数字串
  • 热度指数:138439 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
输入一个字符串,返回其最长的数字子串,以及其长度。若有多个最长的数字子串,则将它们全部输出(按原字符串的相对位置)
本题含有多组样例输入。

数据范围:字符串长度 , 保证每组输入都至少含有一个数字

输入描述:

输入一个字符串。1<=len(字符串)<=200



输出描述:

输出字符串中最长的数字字符串和它的长度,中间用逗号间隔。如果有相同长度的串,则要一块儿输出(中间不要输出空格)。

示例1

输入

abcd12345ed125ss123058789
a8a72a6a5yy98y65ee1r2

输出

123058789,9
729865,2

说明

样例一最长的数字子串为123058789,长度为9
样例二最长的数字子串有72,98,65,长度都为2    
def length(s: str):

    num_len = 0
    num_key = ''
    num_dict = {}

    for i in range(len(s)):

        if s[i].isdigit():
            num_len += 1
            num_key = num_key + s[i]
        else:
            if num_len >= 1:
                try:
                    num_dict[num_len] += num_key
                except:
                    num_dict[num_len] = ''
                    num_dict[num_len] += num_key
                num_len = 0
                num_key = ''
        if (i == len(s)-1) and s[i].isdigit():
            try:
                num_dict[num_len] += num_key
            except:
                num_dict[num_len] = ''
                num_dict[num_len] += num_key
    
    return num_dict

while True:
    try:
        def_dict = length(input())
        max_len = max(def_dict.keys())
        print(def_dict[max_len] + ',' + str(max_len))
    except:
        break

编辑于 2024-04-10 14:59:27 回复(0)
for line in sys.stdin:
    a = line.strip()
    b=[str(i) for i in range(10)]
    l=['']
    max=0
    for i in a:
        if i not in b and l[-1]!="":
            if len(l[-1])>max:
                max=len(l[-1])
            l.append("")
        elif i in b:
            l[-1]+=i
    if len(l[-1])>max:
        max=len(l[-1])
    s=''
    for i in l:
        if len(i)==max:
            s+=i
    print(s+','+str(max))

编辑于 2024-03-26 14:58:53 回复(0)
def fun(str):
    dic = {}
    lef = 0
    right = 0
    while lef < len(s):
        if s[lef].isdigit() == True:
            right = lef + 1
            while s[right].isdigit():
                right += 1
                # a = s[right] 用来看right到哪里了,后续超过下标一直报错
                # 如果把这行代码放在上面就没有这个风险了,因为判断语句能使用
                if right < len(s):
                    continue
                else:
                    break
            str = s[lef:right]
            dic[str] = len(str)
            lef = right
        else:
            lef += 1
            right = lef
    max = sorted(dic.values())[-1]
    max_key = ""
    for key, val in dic.items():
        if val == max:
            max_key = max_key + key
    print(max_key, end=",")
    print(val)


while True:
    try:
        s = input()
        fun(s)
    except:
        break
编辑于 2024-03-19 22:46:38 回复(0)
import re

while True:
    try:
        s = input()
        pattern = r"\d+"
        a = re.findall(pattern, s)
        b = sorted(a, key=lambda x: len(x), reverse=True)
        maxlen = len(b[0])
        c = "".join([i for i in b if len(i) == maxlen])
        print(f"{c},{maxlen}")
    except:
        break
编辑于 2023-12-02 03:24:16 回复(0)
import re
''' 利用正则表达式取出所有数字子串,按照长度进行排序'''
while True:
    try:
        s = input()
        temp = sorted(re.findall('[0-9]+',s),key=len,reverse=True)
        l = len(temp[0])
        res = [i for i in temp if len(i)==l]
        print(f"{''.join(res)},{l}")
    except:
        break

发表于 2023-07-25 18:43:33 回复(0)

双指针

while True:
    try:
        s = input()
        # s = "abcd12345ed125ss123058789"
        n = len(s)
        ans = []
        left = 0
        right = 0
        flag = 0
        max_len = 0
        while right < n:
            while right<n and not s[right].isnumeric():
                right += 1
            flag = 1
            left = right
            while right< n and s[right].isnumeric():
                right += 1
            if right - left >= max_len:
                ans.append((left, right))
                max_len = right - left
                flag = 0
            left = right
        if flag:
            ans.append((left, n))
        for left,right in ans:
            if right-left==max_len:
                print(s[left : right],end="")
        print(f",{max_len}")
    except:
        break
发表于 2023-07-21 11:31:07 回复(0)
while True:
    try:
        ret = []
        s = input()
        for i in range(len(s) + 1):
            for j in range(i):
                _s = s[j:i]
                if _s.isdigit():
                    ret.append(_s)
        max_num = max([len(i) for i in ret])
        new_s = "".join(list(map(lambda x: x if len(x) == max_num else "", ret)))
        print(f"{new_s},{max_num}")
    except Exception as e:
        break
发表于 2023-05-08 22:58:57 回复(0)
a = input()
s = ""
l = []
for i in a:
    if i.isdigit():
        s += i
        l.append(s)
    else:
        s = ""
lenth = len(max(l, key=len))
for j in l:
    if len(j) == lenth:
        print(j, end="")
print(f",{lenth}")

发表于 2023-03-26 20:10:32 回复(0)
import sys

while True:
    try:
        ss = input()
        dic = {}
        max_len = 0
        left, right = 0, 0
        while right < len(ss):
            if not ss[left].isdigit():
                left += 1
                right = left
            else:
                while right < len(ss) and ss[right].isdigit():
                    right += 1
                sub = ss[left:right]
                length = right - left
                if length not in dic:
                    dic[length] = sub
                else:
                    dic[length] += sub
                max_len = max(length, max_len)
                left = right

        if max_len != 0:
            print(str(dic[max_len])+','+str(max_len))


    except:
        break

发表于 2023-03-21 00:12:34 回复(0)
import sys
while True:
    try:
        s = input()
        res = ''
        count = 0
       
        for i in range(len(s)):
            for j in range(1,len(s)+1):
                if s[i:j].isdigit() and (j-i) == count:
                    res += s[i:j]
                elif s[i:j].isdigit() and (j-i)>count:
                    res = s[i:j]
                    count = j-i
        print(res,end = ',')
        print(count)
    except:
        break
发表于 2023-03-06 21:51:08 回复(0)
while True:
    try:
        s = input()
        s1 = ''
        for i in s:
            if i.isalpha():
                s1 += ' '
            else:
                s1 += i
        
        l = list(s1.split())
        len_l = []
        for i in l:
            len_l.append(len(i))
        for i in l:
            if len(i) == max(len_l):
                print(i,end='')
        print(',',end='')
        print(max(len_l))
    except:
        break

发表于 2023-02-26 12:35:42 回复(0)

number = "0123456789"
for line in sys.stdin:
    a= line.split("\n")[0]
    i,j = 0,0
    max_length = 0
    temp = []
    while i <len(a) and j < len(a):
        if a[i] in number:
            j = i
            while j < len(a) and a[j] in number:
                j += 1
                max_length = max(max_length,j-i)
            temp.append(a[i:j])
            i = j
                   
        else:
            i += 1
    res = ''
    for i in temp:
        if len(i) == max_length:
            res += i
    print(str(res) + "," + str(max_length))

发表于 2023-02-20 22:22:02 回复(0)
#不用re
while True:
    try:
        s=input()
        for i in s:
            if not i.isdigit():
                s=s.replace(i,' ')
        s=s.split(' ')
        l=0
        ss=''
        for i in s:
            if len(i)>l:
                l=len(i)
        for i in s:
            if len(i)==l:
                ss+=i
        print(ss,end=',')
        print(l)
    except:
        break


#用re
import re
while True:
    try:
        s=input()
        pattern=re.compile(r'\d+')
        s=pattern.findall(s)
        s=sorted(s,key=lambda x:len(x),reverse=True)
        l=len(s[0])
        ss=''
        for i in s:
            if len(i)>=l:
                ss+=i
        print(ss+','+str(l))
    except:
        break

发表于 2023-02-17 12:05:32 回复(0)
import re
while True:
    try:
        s = sorted(re.findall(r'[0-9]+', input()), key=lambda x: -len(x))
        max = len(s[0])
        for i in s:
            if len(i) == max:
                print(str(i), end="")
        print(','+str(max))
    except:
        break
# 用正则提取所有数字串,以长度的负数为依据进行排序,然后输出长度等于最大长度的字符串
发表于 2022-11-22 19:09:25 回复(0)
字母换空格,拆分字符串后,找出最大长度,然后筛选输出
import sys
import re

for line in sys.stdin:
    p=re.compile("[a-zA-Z]")
    s1=line[:-1]
    tmp=re.sub(p," ",s1).split()
    max_len=max([len(x) for x in tmp])
    res=""
    for i in tmp:
        if len(i)==max_len:
            res+=i
            
    print("{0},{1}".format(res,max_len))


发表于 2022-09-26 19:11:41 回复(0)
#自己调了半天的笨方法
def longnum(s):
    res = ''
    cur = ''
    pre = ''
    n = 0
    for x in s:
        if x.isdigit():
            cur += x
        else:
            if pre.isdigit() == True:#这串数字结束
                if len(cur) > n:
                    res = cur
                    n = len(cur)
                elif len(cur) == n:#长度相同,加后面,n不变
                    res += cur
                cur = ''
        pre = x 
    if len(cur) > n:#最后一位是数字,再判断一下
        res = cur
        n = len(cur)
    elif len(cur) == n: 
        res += cur
    return res,n

while True:
    try:
        s = input()
        l,n = longnum(s)
        print(l + ',' + str(n))
    except:
        break
        

发表于 2022-09-18 10:47:30 回复(0)
import sys

def isnum(char):
    if char >= '0' and char <= '9':
        return True
    return False

def numstring(s):
    l =len(s)
    ns = []
    nums = ''
    lgest = 1
    for i in range(l-1):
        if not isnum(s[i]) and isnum(s[i+1]):
            s = s.replace(s[i], '#')
        elif isnum(s[i]) and not isnum(s[i+1]):
            s = s.replace(s[i+1], '#')
    ns = s.split('#')

    for string in ns:
        if len(string) == 0:
            continue
        if isnum(string[0]):
            lgest = max(lgest, len(string))

    for string in ns:
        if len(string) == lgest and isnum(string[0]):
            print(string,end='')

    print(','+str(lgest)) 

for line in sys.stdin:
    a = line.split()
    numstring(a[0])

发表于 2022-09-16 20:10:39 回复(0)