[英]Fast replacing characters in a string and checking if a substring is a palindrome
在程序的輸入處接收到一行,其長度不超過 10^5。
在這之后出現了很多兩種類型的指令:
set l r c (l - start of substring, r - end of substring, c - character to replace all substring characters)
ask l r (l - start of substring, r - end of substring)
1 ⩽ l ⩽ r ⩽ string length
Set
命令,用給定的字符替換所有子串字符。 並且ask
命令必須檢查子串是否是回文。
例如,如果程序在輸入端接收到這樣的數據
5 5 - line length and number of commands
abcde
ask 1 5
set 2 4 z
ask 2 4
set 5 5 a
ask 5 5
然后作為回應,她將打印:
NO
YES
YES
我的實施非常不理想。 它有效,但時間太長了。 請告訴我一個更快的算法。
def p(s):
for i in range(len(s)//2):
if s[i]!=s[-1-i]:
return False
return True
N,Q = [int(i) for i in input().split()]
s = list(input())
for i in range(Q):
c = input().split()
if c[0]=='set':
s[int(c[1])-1:int(c[2])] = [c[3]]*(int(c[2])-int(c[1])+1)
elif c[0]=='ask':
if p(s[int(c[1])-1:int(c[2])]):
print('YES')
else:
print('NO')
在替換一些子字符串后,實現對所有回文單獨搜索。
def allPalindromeSubstring(s):
v = {}
pivot = 0.0
while pivot < len(s):
palindromeRadius = pivot - int(pivot)
while ((pivot + palindromeRadius) < len(s) and
(pivot - palindromeRadius) >= 0 and
(s[int(pivot - palindromeRadius)] ==
s[int(pivot + palindromeRadius)])):
l = int(pivot - palindromeRadius) + 1
r = int(pivot + palindromeRadius + 1)
if l in v:
v[l].append(r)
else:
v[l] = [r]
palindromeRadius += 1
pivot += 0.5
return v
N,Q = [int(i) for i in input().split()]
s = list(input())
ps = allPalindromeSubstring(s)
for i in range(Q):
c = input().split()
l = int(c[1]); r = int(c[2])
if c[0]=='set':
s[l-1:r] = [c[3]]*(r-l+1)
ps = allPalindromeSubstring(s)
elif c[0]=='ask':
b = True
if l in ps:
for j in ps[l]:
if r<=j:
print('YES')
b = False
break
if b:
print('NO')
我沒有足夠的數據來為我的新代碼計時。 但這必須比你的快:)
import numpy as np
from math import ceil
N, Q = [int(i) for i in input().split()]
s = np.asarray(list(input()), dtype="unicode")
for i in range(Q):
c = input().split()
if c[0] == 'set':
s[int(c[1]) - 1:int(c[2])] = c[3]
elif c[0] == 'ask':
st, ed = int(c[1]) - 1, int(c[2]) - 1
if np.array_equal(s[st:st+ceil((ed-st)/2)+1], s[ed:st+ceil((ed-st)/2)-1:-1]):
print('YES')
else:
print('NO')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.