A-Z
is being encoded to numbers using the following mapping:
'A' -> 1 'B' -> 2 ... 'Z' -> 26Given 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.解题思路:
1. 与climbstairs非常相似,只是这里多加了一些限制条件
f(n) = f(n-2) 当n为0时。
f(n) = f(n-1) 当大于26
容易出错点: 当遇到0的时候,需要判断。
public int numDecodings(String s) { int n = s.length(); if (n == 0 || s.charAt(0) == '0') { return 0; } int num0 = 1, num1 = 1, num = 1; for (int i = 1; i < n; i++) { if(s.charAt(i) != '0'){ num = num1; }else{ num = 0; } if(s.charAt(i-1) != '0' && Integer.valueOf(s.substring(i-1, i+1)) <= 26){ num += num0; } if(num == 0) return 0; num0 = num1; num1 = num; } return num; }
No comments:
Post a Comment