zoukankan      html  css  js  c++  java
  • 剑指offer-46 把数字翻译成字符串

    1  0-25    a-z

    // 面试题46:把数字翻译成字符串
    // 题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成"a",1翻
    // 译成"b",……,11翻译成"l",……,25翻译成"z"。一个数字可能有多个翻译。例
    // 如12258有5种不同的翻译,它们分别是"bccfi"、"bwfi"、"bczi"、"mcfi"和
    // "mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。
    
    #include <string>
    #include <iostream>
    
    using namespace std;
    
    int GetTranslationCount(const string& number);
    
    int GetTranslationCount(int number)
    {
        if (number < 0)
            return 0;
    
        string numberInString = to_string(number);//转换成字符串
        return GetTranslationCount(numberInString);
    }
    
    int GetTranslationCount(const string& number)
    {
        int length = number.length();
        int* counts = new int[length];
        int count = 0;
    
        for (int i = length - 1; i >= 0; --i)//从右开始计算,避免递归中碰到重复的子问题
        {
            count = 0;
            if (i < length - 1)
                count = counts[i + 1];
            else
                count = 1;
    
            if (i < length - 1)
            {
                int digit1 = number[i] - '0';
                int digit2 = number[i + 1] - '0';
                int converted = digit1 * 10 + digit2;
                if (converted >= 10 && converted <= 25)//满足条件,记录当前位置所有可能的次数
                {
                    if (i < length - 2)//有点动态规划的意思
                        count += counts[i + 2];
                    else
                        count += 1;
                }
            }
    
            counts[i] = count;
        }
    
        count = counts[0];//返回counts第一个值
        delete[] counts;
    
        return count;
    }
  • 相关阅读:
    zyb的面试
    Codeforces Round #514 (Div. 2)
    Maximum GCD(fgets读入)
    Harmonic Number(调和级数+欧拉常数)
    Codeforces Round #516 (Div. 2, by Moscow Team Olympiad)
    Sigma Function (平方数与平方数*2的约数和是奇数)
    Leading and Trailing (数论)
    【贪心】【CF3D】 Least Cost Bracket Sequence
    【套题】qbxt国庆刷题班D1
    【极值问题】【CF1063B】 Labyrinth
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11401890.html
Copyright © 2011-2022 走看看