• 剑指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;
    }
  • 相关阅读:
    php 数组处理
    PHP 递归几种方法
    PHP取一算法
    oracle的db link
    sql2008破解加密存储过程
    ATT 解锁手机
    jQuery 通配符
    win10 Enable developer Mode
    Win8.1 远程桌面 凭据无法工作
    html5media.js 让浏览器兼容<Video><Audio> 标签
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11401890.html
Copyright © 2020-2023  润新知