网易算法第一题
给一个字符串,求查询的区间包含多少个长度为3且字符相同的连续字串。例如aaabbbb,查询【1,6】答案是2,查询【1,7】答案是3。
从大佬那边知道这道题用前缀和做,但我还是想知道为啥我的写法只能过13.33,查了老半天,哪里逻辑有问题呢?
n, k = map(int, input().split())
s = input()
query = [] #存储查询区间
for _ in range(k):
l, r = map(int, input().split())
query.append([l-1,r-1])
res = [0] * k
dp = [0] * n
for i in range(n):
# i开头,j结尾
for j in range(i, n):
if j - i < 2:
dp[j] = 0
elif j - i == 2 and len(set(s[i:j+1])) == 1: # 长度为3
dp[j] = 1
else: # 长度等于3但不满足条件或长度大于3
dp[j] = dp[j-1] + (s[j] == s[j-1] and s[j] == s[j-2])
if [i,j] in query: #如果该区间需要查询
idx = query.index([i,j])
res[idx] = dp[j]
print(dp)
#打印结果
for i in res:
print(i)
从大佬那边知道这道题用前缀和做,但我还是想知道为啥我的写法只能过13.33,查了老半天,哪里逻辑有问题呢?
n, k = map(int, input().split())
s = input()
query = [] #存储查询区间
for _ in range(k):
l, r = map(int, input().split())
query.append([l-1,r-1])
res = [0] * k
dp = [0] * n
for i in range(n):
# i开头,j结尾
for j in range(i, n):
if j - i < 2:
dp[j] = 0
elif j - i == 2 and len(set(s[i:j+1])) == 1: # 长度为3
dp[j] = 1
else: # 长度等于3但不满足条件或长度大于3
dp[j] = dp[j-1] + (s[j] == s[j-1] and s[j] == s[j-2])
if [i,j] in query: #如果该区间需要查询
idx = query.index([i,j])
res[idx] = dp[j]
print(dp)
#打印结果
for i in res:
print(i)
全部评论
感觉可能是重复查询的问题,重复查询只会给第一次出现的查询赋值
相关推荐
![](https://static.nowcoder.com/fe/file/oss/1715049343797JOCFB.png)
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享