leetcode_Decode Ways

来源:互联网 发布:剑侠情缘3网游mac 编辑:程序博客网 时间:2024/06/14 10:55

描述:

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.

思路:

直接从后面开始算,如果str.substring(i,i+2)代表的数值小于26,那么,memo[i]=memo[i+1]+memo[i+2];否则,memo[i]=memo[i+1],虽然看起来很简单,却是很难想,一般都是从前面开始,然后比较字符的值再做判断,这样的话控制逻辑会非常复杂。

代码:

public int numDecodings(String s){int strLen=s.length();if(strLen==0)return 0;int memo[]=new int[strLen+1];memo[strLen]=1;memo[strLen-1]=s.charAt(strLen-1)!='0'?1:0;for(int i=strLen-2;i>=0;i--){if(s.charAt(i)=='0')continue;else {memo[i]=(Integer.parseInt(s.substring(i,i+2)))<=26?memo[i+1]+memo[i+2]:memo[i+1];}}return memo[0];}


0 0
原创粉丝点击