Python 寻找一个数的下一个最大回文的两种方法的复杂性

Python 寻找一个数的下一个最大回文的两种方法的复杂性,python,time-complexity,palindrome,Python,Time Complexity,Palindrome,我在网上遇到了一个关于下一个最大回文的问题,我用python中的两种不同方法解决了这个问题。一是, t = long(raw_input()) for i in range(t): a = (raw_input()) a = str(int(a) + 1) palin = "" oddOrEven = len(a) % 2 if oddOrEven: size = len(a) / 2 center = a[size]

我在网上遇到了一个关于下一个最大回文的问题,我用python中的两种不同方法解决了这个问题。一是,

t = long(raw_input())

for i in range(t):
    a = (raw_input())
    a = str(int(a) + 1)
    palin = ""
    oddOrEven = len(a) % 2

    if oddOrEven:
        size = len(a) / 2
        center = a[size]
    else:
        size = 0
        center = ''

    firsthalf = a[0 : len(a)/2]
    secondhalf = firsthalf[::-1]
    palin = firsthalf + center + secondhalf

    if (int(palin) < int(a)):
        if(size == 0):
            firsthalf = str(int(firsthalf) + 1)
            secondhalf = firsthalf[::-1]
            palin = firsthalf + secondhalf

        elif(size > 0):
            lastvalue = int(center) + 1

            if (lastvalue == 10):
                firsthalf = str(int(firsthalf) + 1)
                secondhalf = firsthalf[::-1]
                palin = firsthalf + "0" + secondhalf

            else:
                palin = firsthalf + str(lastvalue) + secondhalf
    print palin
t=long(原始输入()
对于范围(t)内的i:
a=(原始输入()
a=str(int(a)+1)
佩林=“”
oddOrEven=len(a)%2
如果oddOrEven:
尺寸=透镜(a)/2
中心=a[尺寸]
其他:
大小=0
中心=“”
前半部分=a[0:len(a)/2]
secondhalf=firsthalf[:-1]
佩林=上半场+中半场+下半场
如果(佩林)0):
lastvalue=int(中间)+1
如果(lastvalue==10):
前半部分=str(int(前半部分)+1)
secondhalf=firsthalf[:-1]
佩林=上半段+0+下半段
其他:
佩林=上半部分+str(lastvalue)+下半部分
打印佩林
另一个是,

def inc(left):
    leftlist=list(left)
    last = len(left)-1
    while leftlist[last]=='9':
        leftlist[last]='0'
        last-=1

    leftlist[last] = str(int(leftlist[last])+1)
    return "".join(leftlist)


def palin(number):
    size=len(number)
    odd=size%2
    if odd:
        center=number[size/2]
    else:
        center=''
    print center
    left=number[:size/2]
    right = left[::-1]
    pdrome = left + center + right
    if pdrome > number:
        print pdrome
    else:
        if center:
            if center<'9':
                center = str(int(center)+1)
                print left + center + right
                return
            else:
                center = '0'
        if left == len(left)*'9':
            print '1' + (len(number)-1)*'0' + '1'
        else:
            left = inc(left)
            print left + center + left[::-1]

if __name__=='__main__':
    t = long (raw_input())
    while t:
        palin(raw_input())
        t-=1
def公司(左): leftlist=列表(左) 最后一个=透镜(左)-1 而leftlist[last]=='9': leftlist[last]=“0” 最后-=1 leftlist[last]=str(int(leftlist[last])+1) 返回“”。加入(左列表) 佩林(编号): 尺寸=长度(数量) 奇数=大小%2 如果为奇数: 中心=数量[尺寸/2] 其他: 中心=“” 打印中心 左=数字[:大小/2] 右=左[:-1] pdrome=左+中+右 如果pdrome>编号: 打印PD罗马 其他: 如果中心:
如果中心我看到您正在for循环中创建一个子列表,最大的子列表大小为n-1。然后是一个到n的循环

所以两者最坏的情况都是O(n^2),其中n是t的长度