字符串解码的方式数量

时间:2019-05-21 19:01:18

标签: python python-3.x recursion

我收到有关ACODE spoj问题的错误答案。谁能帮助我弄清楚我犯了什么错误。这是SPOJ编码问题(https://www.spoj.com/problems/ACODE/)。

我手动尝试了许多测试用例,但它们似乎运行良好。我不知道它在哪里失败。有人帮忙。

我已经应用了递归方法

#https://www.spoj.com/problems/ACODE/

def countPossibleCombinations(encoded,start,length,saved):
    global count
    if (length-start)==0:
        return 0
    elif (length-start)==1:
        return 1
    elif (length-start)==2:
        if int(encoded[start:])<27:
            return 2
        else:
            return 1
    try:
        x = saved[start]
        return x
    except:
        pass
    total = 0
    try:
        val1 = saved[start+1]
    except:
        val1 = countPossibleCombinations(encoded,start+1,length,saved)
    if int(encoded[start:start+2])<27:
        try:
            val2 = saved[start+2]
        except:
            val2 = countPossibleCombinations(encoded,start+2,length,saved)
        total = val1+val2
    else:
        total = val1
    saved[start] = total
    return total

def countPossibleMessages(encoded):
    strings = [string for string in encoded.split('0') if len(string)>0]
    strings1 = []
    for string in strings:
        if len(string[:-1])==0:
            pass
        elif int(string[-1])<3:
            strings1 += [string[:-1]]
        else:
            strings1 += [string]
    if encode[-1]!="0":
        strings1[-1] = strings[-1]
    #print(strings1)
    num = 1
    for string in strings1:
        saved = {}
        num = num*countPossibleCombinations(string,0,len(string),saved)
    return num

while True:
    try:
        encode = str(input())
        if encode=="0":
            break

        print(countPossibleMessages(encode))
    except Exception as e:
        print(0)

我得到了错误的答案。

0 个答案:

没有答案