ACwing 4261. 孤独的照片

文章讨论了一道ACwing上的编程题目4261,题目涉及寻找字符串中特定模式的子串。提供的错误代码在Python环境下运行时出现RuntimeError和TimeLimitExceeded的问题。文章提供了正确的解决方案,该方案避免了可能导致超时的操作,如不必要的字符串遍历和插入操作。
摘要由CSDN通过智能技术生成

ACwing 4261. 孤独的照片

错误题解

# acwing 4261. 孤独的照片

# 输入数字和字符串
lenth=int(input())
strr=input()

# 遍历count计数
count=0
for starts in range(0,lenth-2):
    for endlen in range(3,lenth-starts+1):
        if strr.count('G',starts,starts+endlen)==1 or strr.count('H',starts,starts+endlen)==1:
            count+=1
print(count)

选择使用python报错

代码提交状态: Runtime Error   
Traceback (most recent call last):
  File "a.py", line 5, in <module>
    strr=input()
  File "<string>", line 1, in <module>
NameError: global name 'GHGHG' is not defined

版本问题,这是python3的语法,但是选的版本不是python3

使用python3

代码提交状态: Time Limit Exceeded   
代码运行状态: 错误数据如下所示
输入
5000
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG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GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG...

输出
标准答案
1025886

正确题解

# acwing 4261. 孤独的照片
lenth=int(input())
strs=input()

li=[]
h=0
g=0
for i in range(0,lenth):
    if strs[i]=='G':
        li.append(h)
        h=0
        g+=1
    else:
        li.append(g)
        h+=1
        g=0
h=0
g=0
ri=[0 for i in range(0,lenth)]
for i in range(lenth-1,-1,-1):
    if strs[i]=='G':
        ri[i]=h
        h=0
        g+=1
    else:
        ri[i]=g
        h+=1
        g=0

count=0
for i in range(0,lenth):
    count+=ri[i]*li[i]+max(ri[i]-1,0)+max(li[i]-1,0)
print(count)

ps: 由于ri是从后面填到前面的,使用insert填充的话会出现超时,应该是python写的那个函数使用的是一个动态数组,插入一个值,就得把已有的值一个一个挪到后面,所以就出现了超时(不过只是猜想)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值