解析字符串算法实现建议

时间:2015-12-18 04:13:39

标签: python algorithm

使用下面的算法难题将包含数字的字符串解码为字符。发布完整的问题陈述和参考代码。实际上我提到了一些解决方案,似乎我找到的所有解决方案都是从后面解码到前面,我认为从前到后解码也应该没问题,只是想知道为什么这个问题有什么特别的好处或考虑因素,那就更好了从后到前解码?感谢。

使用以下映射将包含来自A-Z的字母的消息编码为数字:

' A' - > 1 ' B' - > 2 ... ' Z' - > 26 给定包含数字的编码消息,确定解码它的总方式。

例如, 给定编码消息" 12",它可以解码为" AB" (1 2)或" L" (12)。

解码方式的数量" 12"是2。

public class Solution {
    public int numDecodings(String s) {
        int n = s.length();
        if (n == 0) return 0;

        int[] memo = new int[n+1];
        memo[n]  = 1;
        memo[n-1] = s.charAt(n-1) != '0' ? 1 : 0;

        for (int i = n - 2; i >= 0; i--)
            if (s.charAt(i) == '0') continue;
            else memo[i] = (Integer.parseInt(s.substring(i,i+2))<=26) ? memo[i+1]+memo[i+2] : memo[i+1];

        return memo[0];
    }
}
提前谢谢, 林

1 个答案:

答案 0 :(得分:2)

如果您将字符串从前到后或从后到前解码,如果将其分解为子字符串并存储其结果,则没有区别。

这实现了前后方法:

def decode_string(st):
    result_dict = {st[0]:1}

    for i in xrange(2,len(st)+1):
        if int(st[i-1]) == 0:
            if int(st[i-2]) not in [1,2]:
                return "Not possible to decode"

            result_dict[st[:i]] = 0

        else:
            result_dict[st[:i]] = result_dict[st[:i-1]]

        if int(st[i-2:i]) < 27 and st[i-2] != '0':
            result_dict[st[:i]] = result_dict[st[:i]] + result_dict.get(st[:i-2],1)

    return result_dict[st]

print decode_string("125312")

result_dict包含增量子字符串的所有可能性。用第一个字符初始化

特别检查&#39; 0&#39;因为0的唯一可接受的值是10和20.因此,如果输入包含其他内容,则从循环中断

然后,对于每个索引,检查与先前索引的组合是否是字符(组合&lt; 27)。如果为true,则将string的结果添加到index-2。

将每个增量子字符串的结果存储在字典中

<强>结果:

result_dict包含如下值:

{'12': 2, '12531': 3, '1': 1, '125312': 6, '125': 3, '1253': 3}

所以result_dict[st]给出了必要的答案

使用列表是一个更好的主意

def decode_string(st):
    result_list = [1]
    for i in xrange(2,len(st)+1):
        if int(st[i-1]) == 0:
            if int(st[i-2]) not in [1,2]:
                return "Not possible to decode"

            result_list.append(0)

        else:
            result_list.append(result_list[i-2])

        if int(st[i-2:i]) < 27 and st[i-2] != '0':
            if i>2:
                result_list[i-1] = result_list[i-1] + result_list[i-3]
            else:
                result_list[i-1] = result_list[i-1] + 1
    print result_list
    return result_list[-1]

print decode_string("125312")
相关问题