leecode 解题总结:91. Decode Ways

来源:互联网 发布:知乎宏远体育怎么样 编辑:程序博客网 时间:2024/05/16 09:23
#include <iostream>#include <stdio.h>#include <vector>#include <unordered_map>#include <string>using namespace std;/*问题:A message containing letters from A-Z is being encoded to numbers using the following mapping:'A' -> 1'B' -> 2...'Z' -> 26Given 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.分析:题目对字符A到Z进行1到26的转换,现在给定数字,要求反推得原先的字母组成的不同字符串的个数A:1,G:7,H:8,I:9,J:10,...,Z:26也就是两位数(11~26,其中不包括20,因为0不能在个位数对应的字母中找到)的解码会产生两种情况:把这个数字认为是两位数,或者拆分成两个一位数。1】凡是遇到当前数为0,一定需要和前面的数字组成一个二位数,2】凡是遇到数字3到9,必然不会和后面的数字组成二位数来解码。也就是说我们可以对字符串进行分割:1】遇到0,0和前面的数字将当前字符串分割成两部分,每部分递归求总数2】遇到3~9,如果前面是1可以组合;2只能和0到6搭配。单独将两边拆分成各个子串进行这样太麻烦了。直接在递归中设定一个合法数的范围,判定如果当前字符串的长度为1或2的时候对应的数字是否在合法数范围中,如果不是,返回该种解码总数为0;如果是,看是否能同时组成一位数或二位数设dp[i]表示字符串从s[1]到s[i]所能得到的解码总数。但是这样会发现,一旦有新字符加入进来会对前面的解码总数有影响,发现:如果采用字符串分割统计的话,有的会被重复统计:比如1120,拆分后,变成1,1,20,统计了一次,而先拆分为11,20算作两次leecode解法:https://leetcode.com/problems/decode-ways/?tab=Solutions有点类似于上台阶问题,每次只能走一步或两布。我们可以设定dp[i]表示长度为i的字符串的解码个数,如果i-1位置上的字符为1~9,dp[i] += dp[i-1]如果i-2到i-1两个字符组成的数字在10~26,dp[i] += dp[i-2]牛逼,每次只考虑当前字符前面两个字符的组合情况输入:121011201121输出:2125关键:1 有点类似于上台阶问题,每次只能走一步或两布。我们可以设定dp[i]表示长度为i的字符串的解码个数,如果i-1位置上的字符为1~9,dp[i] += dp[i-1]如果i-2到i-1两个字符组成的数字在10~26,dp[i] += dp[i-2]牛逼,每次只考虑当前字符前面两个字符的组合情况*/class Solution {public:    int numDecodings(string s) {if(s.empty()){return 0;}int len = s.length();vector<int> dp(len + 1 , 0);dp.at(0) = 1;//起始位置设定只有一种解法dp.at(1) = s.at(0) != '0' ? 1 : 0;//如果为0,肯定不行int second;string sSecond;char firstChar;for(int i = 2 ; i <= len ; i++){firstChar = s.at(i-1);sSecond = s.substr(i-2 , 2);//截取第i-2和i-2字符//等同于包含了对于当前字符i前面两个字符的组合请款判断second = atoi((char*)sSecond.c_str());if('1' <= firstChar && firstChar <= '9'){dp[i] += dp[i-1];}if(10 <= second && second <= 26){dp[i] += dp[i-2];}}return dp[len];    }};void process(){ string value; Solution solution; while(cin >> value ) { int result = solution.numDecodings(value); cout << result << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击