HJ92_在字符串中找出连续最长的数字串_技巧

思路:按照模拟思路,没有技巧地,代码如2。

新思路:把非数字转换成空格,使用空格作为标记切片。

!!!

注意:字符串变更,要用replace()方法生成新字符串!!!

 

参考高赞答案,重写代码如1:

复制代码
 1 import sys
 2 a=[]
 3 for line in sys.stdin:
 4     a.append(line.strip())
 5 for i in a:
 6     for j in range(len(i)):
 7         if not i[j].isdigit():
 8             i=i.replace(i[j]," ")#i[j]=" ",字符串变更不可通过赋值方法,只能通过replace()方法生成新字符串
 9     new=i.split()
10     c=[len(i) for i in new]
11     s=""
12     for i in new:
13         if len(i)==max(c):
14             s=s+i
15     print(",".join([s,str(max(c))]))
复制代码

 

复制代码
 1 import sys
 2 a=[]
 3 for line in sys.stdin:
 4     a.append(line.strip())
 5 for i in a:
 6     c=-1
 7     l1=[]
 8     l,ind=[],[]
 9     for j in i:
10         c+=1
11         
12         if j.isdigit():
13             #print(j,l)
14             if l:
15                 if c-1==ind[-1]:
16                     l.append(j)
17                     ind.append(c)
18                 else:
19                     #print(j)
20                     l1.append(l.copy())
21                     l,ind=[],[]
22                     l.append(j)
23                     ind.append(c)
24                 if c==len(i)-1:
25                     l1.append(l.copy())
26                     #print(j,l1)
27             else:
28                 #print(j)
29                 l.append(j)
30                 ind.append(c)
31     lenth=[len(i) for i in l1]
32     new=""
33     for i in l1:
34         if len(i)==max(lenth):
35             new=new+"".join(i)
36     print(",".join([new,str(max(lenth))]))
复制代码

 

posted @   Aneverforget  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示