leetCode练习(91)
2016-10-25 09:41
211 查看
题目:Decode Ways
难度:medium
问题描述:
A message containing letters from
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message
The number of ways decoding
解题思路:使用动态规划的方法。从str.length=1开始一直计算到length=n. 其中,count
与count[n-1]和count[n-1]有关。具体情况有:
char[I]=0时,char[I-1]大于2或者等于0,无解count[I]=0 。char[I-1]=1或2时,count[I]=count[I-2].
char[I]!=0时,sum=10*char[I-1]+char[I]; 如果sum>26或者sum<10,count[I]=count[I-1].否则 count[I]=count[I]+count[I-1]。
具体代码如下:
难度:medium
问题描述:
A message containing letters from
A-Zis 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.length=1开始一直计算到length=n. 其中,count
与count[n-1]和count[n-1]有关。具体情况有:
char[I]=0时,char[I-1]大于2或者等于0,无解count[I]=0 。char[I-1]=1或2时,count[I]=count[I-2].
char[I]!=0时,sum=10*char[I-1]+char[I]; 如果sum>26或者sum<10,count[I]=count[I-1].否则 count[I]=count[I]+count[I-1]。
具体代码如下:
public static int numDecodings(String s) { if(s==null||s.equals("")){ return 0; } if(s.length()==1){ return s.equals("0")?0:1; } int len=s.length(); int lasttwo,lastone; int temp; int lastchar=s.charAt(0)-'0'; int sum; if(lastchar==0){ return 0; } if(s.charAt(1)=='0'){ if(lastchar>2){ return 0; }else{ lasttwo=1; lastone=1; } }else{ sum=lastchar*10+s.charAt(1)-'0'; if(sum>26){ lasttwo=1; lastone=1; }else{ lasttwo=1; lastone=2; } } lastchar=s.charAt(1)-'0'; for(int i=2;i<len;i++){ temp=s.charAt(i)-'0'; if(temp==0){ if(lastchar>2||lastchar==0){ return 0; }else{ lastchar=temp; int a=lasttwo; lasttwo=lastone; lastone=a; } }else{ sum=lastchar*10+temp; if(sum<10||sum>26){ lastchar=temp; lasttwo=lastone; //lastone 不变 }else{ lastchar=temp; int a=lasttwo; lasttwo=lastone; lastone=a+lastone; } } } return lastone; }
相关文章推荐
- 经典C++笔试题目--100(编程练习(比C要难)(91-100))
- 数据结构与算法 LeetCode编程练习--Delete Node in a Linked List
- leetcode 刷题之路 91 Pascal's Triangle
- [leetcode91]Restore IP Addresses(java)
- [LeetCode]91 Decode Ways
- Leetcode练习-Binary Tree Inorder Traversal
- Leetcode练习- Merge Two Sorted List
- leetCode练习(75)
- leetCode练习(242)
- 『LeetCode』练习第一弹_算法1,2题
- SQL查询练习一(From LeetCode)
- LeetCode(91) Decode Ways
- leetCode练习(90)
- leetCode练习(3)
- leetCode练习(4)
- LeetCode Online Judge 题目C# 练习 - Insert Interval
- leetCode练习(111)
- LeetCode练习-简单卷
- 常见算法练习leetcode
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II