繁体   English   中英

快速替换字符串中的字符并检查子字符串是否为回文

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM