[leetcode] Decode Ways
来源:互联网 发布:做网页用什么软件 编辑:程序博客网 时间:2024/06/01 03:57
A message containing letters from A-Z
is being encoded to numbers using the following mapping:
'A' -> 1'B' -> 2...'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12"
, it could be decoded as "AB"
(1 2) or "L"
(12).
The number of ways decoding "12"
is 2.
思路: 在解码过程中,可以选择两个字符,可以选择一个字符,所以要分别考虑,利用动态规划解决,如果选择两个字符且两个字符满足要求,且选择一个字符的时候该字符非0, 则有tmp[i] = tmp[i-1] + tmp[i-2]。但注意考虑"0*"的双字符情况。且初始边界条件也要注意,代码比较繁琐。
class Solution: # @param s, a string # @return an integer def numDecodings(self, s): if len(s) == 0: return 0 if len(s) == 1: if int(s) <= 0: return 0 else: return 1 tmp = [0 for x in range(len(s))] if int(s[0]) != 0: tmp[0] = 1 else: tmp[0] = 0 if int(s[0:1]) > 26 and int(s[1]) == 0: tmp[1] = 0 elif int(s[1]) == 0 and int(s[0:2]) <= 26: tmp[1] = tmp[0] elif int(s[1]) != 0 and int(s[0:2]) > 26: tmp[1] = tmp[0] elif int(s[1]) != 0 and int(s[0:2]) <= 26: if s[0] == '0': tmp[1] = 0 else: tmp[1] = 2 for i in range(2,len(s)): if int(s[i-1:i+1]) > 26 and int(s[i]) == 0: tmp[i] = 0 elif int(s[i]) == 0 and int(s[i-1:i+1]) <= 26: if s[i-1] == '0': tmp[i] = 0 else: tmp[i] = tmp[i-2] elif int(s[i-1:i+1]) > 26 and int(s[i]) > 0: tmp[i] = tmp[i-1] else: if s[i-1] == '0': tmp[i] = tmp[i-1] else: tmp[i] = tmp[i-1] + tmp[i-2] return tmp[len(s)-1]
0 0
- Leetcode 91. Decode Ways&&639.Decode ways
- LeetCode: Decode Ways
- [LeetCode]Decode Ways
- LeetCode Decode Ways
- LeetCode : Decode Ways
- [Leetcode] Decode Ways *
- [leetcode] Decode Ways (!!)
- leetcode 17: Decode Ways
- Leetcode: Decode ways
- LeetCode Decode Ways
- [LeetCode]Decode Ways
- [leetcode] Decode Ways
- Leetcode: Decode Ways
- [LeetCode] Decode Ways
- [leetcode]Decode Ways
- LeetCode-Decode Ways
- [leetcode] Decode Ways
- [LeetCode] Decode Ways
- 我的第一个FPGA软核: Small Simple FPU
- UIApplication解析
- Mathematical aspects of finite element I (有限元的数学概念)
- 【编程之美】微软技面心得
- 有序矩阵中查找第k小的元素 Kth smallest element in a row-wise and column-wise sorted 2D array
- [leetcode] Decode Ways
- Remove Duplicates from Sorted List II
- Reverse Linked List
- appcompat_v7 与 actionbarsherlock 冲突解决/移除项目中的appcompat_v7
- python 函数小结
- R apply, lapply, sapply, mapply, tapply functions
- OpenWrt的差异化特性介绍
- Reverse Linked List II
- 接口设备发包