[Leetcode] Decode Ways

来源:互联网 发布:ubuntu没有 ssh目录 编辑:程序博客网 时间:2024/05/21 11:36

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.

public class Solution {    public int numDecodings(String s) {        if(s.length() == 0){            return 0;        }                int[] result = new int[s.length() + 1];        result[s.length()] = 1;        for(int i = s.length() - 1; i >= 0; i--) {            if(s.charAt(i) == '0') {                result[i] = 0;                continue;            }                        result[i] = result[i + 1];            if(canTakeTwoChar(s, i)) {                result[i] += result[i+2];            }        }        return result[0];    }        private boolean canTakeTwoChar(String s, int position) {        if(s.charAt(position) == '0') {            return false;        }        else if(position >= s.length() - 1){            return false;        }                int value = (s.charAt(position) - '0') * 10 + (s.charAt(position + 1) - '0');        return value <= 26;    }}

0 0
原创粉丝点击