剑指offer-面试题46-把数字翻译成字符串-动态规划

/*
题目:
	给定一个数字,将0~25依次翻译为a~z,计算有多少种翻译方法。
*/
/*
思路:
	动态规划法
*/
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>


using namespace std;



int GetTranslationCount(string number){
    int length = number.size();
    if(length == 0 || length == 1){
        return length;
    }
    int n_next = 1;//当前数字的下下个字符
    int next = 2;//当前字符的下个字符
    if(number.substr(length-2,2) > "25"){
        next = 1;
    }
    int curr = next;
    for(int i = length - 3; i >= 0; i--){
        if(number.substr(i,2) > "25"){
            curr = next;
        }else{
            curr = next + n_next;
        }
        n_next = next;
        next = curr;
    }
    return curr;
}

int main(){
    string a = "12258";
    cout<<GetTranslationCount(a);
    return 0;
}

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/12031474.html
今日推荐