首页 > 试题广场 >

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

[编程题]在字符串中找出连续最长的数字串
  • 热度指数:145682 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给定的由数字和小写字母混合构成的字符串 s,找到其中最长的数字子串。如果由多个相同长度的数字子串,则需要全部输出,具体输出的格式请参考输出描述。

\hspace{15pt}子串为从原字符串中,连续的选择一段字符(可以全选、可以不选)得到的新字符串。

输入描述:
\hspace{15pt}输入一个长度为 1 \leqq {\rm len}(s) \leqq 200、由数字和小写字母混合构成的字符串 s。保证至少存在一个数字子串。


输出描述:
\hspace{15pt}记最长的数字子串长度为 l,有 m 个长度为 l 的数字子串。在一行上先首尾相连的输出 m 个长度为 l 的数字子串(不使用空格分割),随后输出一个逗号,再输出 l
示例1

输入

abcd12345ed125ss123058789

输出

123058789,9
示例2

输入

11a22b33c

输出

112233,2

说明

\hspace{15pt}在这个样例中,数字子串 \texttt{ 长度均为 2,都是最长的数字子串。

备注:
\hspace{15pt}本题数据已规范为单组询问(2025/01/15)。
A = []
while 1:
    try:
        A.append(input())
    except:
        break
for i in range(len(A)):
    left, right = 0, 0
    str1 = []
    sum = 0
    while left < len(A[i]):
        if not A[i][left].isdigit():
            left += 1
        else:
            right = left + 1
            while right < len(A[i]) and A[i][right].isdigit():
                right += 1
            if sum < right - left:
                sum = right - left
                str1.clear()
                str1.append(A[i][left:right])
            elif sum == right - left:
                str1.append(A[i][left:right])
            left = right
    print("".join(str1) + "," + str(sum))

发表于 2025-01-11 12:24:32 回复(1)
while True:
    try:
        s = input()
        temp_long = 0
        max_long = 0
        c = []
        d = ''
        # 求最长子串的长度
        for i in range(len(s)):
            if s[i].isdigit():
                temp_long+=1
            else:
                c.append(temp_long)
                temp_long = 0
        c.append(temp_long)
        max_long = max(c)

        # 求最长子串
        temp_long = 0
        for i in range(len(s)):
            if s[i].isdigit():
                temp_long += 1
                if temp_long == max_long:
                    d += s[i-max_long+1:i+1]

            else:
                temp_long = 0
        print(f"{d},{max_long}")

    except:
        break

有点麻烦了
发表于 2025-01-05 21:52:42 回复(0)
import re
import sys

for line in sys.stdin:
    s1 = re.sub(r"\D", " ", line)
    s1 = s1.split()
    s2 = list(map(len, s1))
    res = ""
    for i in s1:
        if len(i) == max(s2):
            res += i
    print(res, max(s2), sep=",")

发表于 2024-09-28 01:12:14 回复(0)
while True:
    try:
        x = input()
        strs = ""
        for i in x:
            if i.isdigit():
                strs+=i
            else:
                strs+=" "
        lists = strs.strip().split(" ")
        len_lists = [len(i) for i in lists]
        max_len = max(len_lists)
        result = []
        for i in lists:
            if len(i)==max_len:
                result.append(i)
        print("".join(result),max_len,sep=",")
    except:
        break
发表于 2024-08-05 09:26:48 回复(0)
def func(s:str):
    res = []
    n = 0  # 记录最长子串的长度值
    longer_detect = False  # 检测到更长的子串时,开启开关
    for i in range(len(s)):
        if s[i-n:i+1].isdigit():  # 下标i+1控制待检测子串总比最大长度值n加了1格
            res = []  # 有更长的子串时,之前res记录的子串都清空
            n += 1
            longer_detect = True
        elif longer_detect:  # 检测最长数字子串后遇到字母,把刚才的子串加入res
            res.append(s[i-n:i])
            longer_detect = False
        elif s[i-n:i].isdigit():  # 以上只将更长的子串加入res,这里处理子串长度和n相同
            res.append(s[i-n:i])
    if s[-n:].isdigit():  # 若末尾最后还有一个n长度纯数字子串,加入res
        res.append(s[-n:])
    
    print(''.join(res)+','+str(n))

while True:
    try:
        s = input()
        func(s)
    except:
        break
发表于 2024-08-04 12:50:07 回复(0)
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)