Decode Ways

来源:互联网 发布:grub安装ubuntu 编辑:程序博客网 时间:2024/06/16 00:19

https://oj.leetcode.com/problems/decode-ways/

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 int numDecodings(String s)

这一题其实就是一个有条件的climbing stairs,实际上当前的解依旧只由前两个子解决定。这是特定条件的f(j) = f(j - 1) + f(j - 2)

实际上f(j - 1)表示的就是用个位数来解读当前这一个位置,f(j - 2)表示的就是联合上一位用两位数的角度来解读当前这个位置。具体条件实际上就看当前位和上一位的数字,然后进行case的分类。

curbit = s.charAt(i) - '0' + (s.charAt(i - 1) - '0') * 10;

1. curbit == 0 ,这样按照规定是不能decode的,直接返回0.

2. curbit 在0 ~ 9。 也就是上一位是0。 那么这个时候就只能取 f(j - 1), 举个例子。("109", "1"  + "09"中的这个"09"并不是有效解读,也就是十位数上不能是0)

3. curbit 在10 ~ 26, 除去10和20之外,都可以是f(j) = f(j - 1) + f(j - 2), 10和20只能取f(j - 2),理由很简单,因为10和20的时候你不能单独解读个位数,那是无效的。

3. curbit > 26,除开所有能被10整除的数只能返回0之外,其余都取f(j - 1)

大致上就这样,下面给出代码:

    public int numDecodings(String s) {        if(s.isEmpty())            return 0;        int cur_way = 1, prev_way = 1, cur_val = 0;        for(int i = 0; i < s.length(); i++){            cur_val = s.charAt(i) - '0' + (i != 0 ? (s.charAt(i - 1) - '0') * 10 : 0);            if(cur_val == 0)                return 0;            else if(cur_val < 10){                prev_way = cur_way;                cur_way = cur_way;            }else if(cur_val <= 26){                if(cur_val % 10 == 0){                    cur_way = prev_way;                    prev_way = 0;                }else{                    cur_way = cur_way + prev_way;                    prev_way = cur_way - prev_way;                }            }else{                if(cur_val % 10 == 0)                    return 0;                prev_way = cur_way;                cur_way = cur_way;            }        }        return cur_way;    }


0 0
原创粉丝点击