Decode Ways
原题链接:https://leetcode.com/problems/decode-ways/#/description
题目:
解题思路:这道题主要是要想到用dynamic programming来保存前一位和前两位的decode方法数。另外一些corner case比如以0开头的或者超过26的需要考虑。
代码:
题目:
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
Given encoded message
"12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding
"12" is 2.解题思路:这道题主要是要想到用dynamic programming来保存前一位和前两位的decode方法数。另外一些corner case比如以0开头的或者超过26的需要考虑。
代码:
public int numDecodings(String s) { if(s == null || s.length() == 0){ return 0; } int[] dp = new int[s.length() + 1]; dp[0] = 1; dp[1] = valid(s.substring(0, 1)) ? 1 : 0; for(int i = 2; i <= s.length() ; i++){ if(valid(s.substring(i - 1, i))){ dp[i] = dp[i - 1]; } if(valid(s.substring(i - 2, i))){ dp[i] += dp[i - 2]; } } return dp[s.length()]; } private boolean valid(String s){ if(s.charAt(0) == '0'){ return false; } int parse = Integer.parseInt(s); return 1 <= parse && parse <= 26; }

Comments
Post a Comment