剑指Offer(第二版)面试题46:把数字翻译成字符串

剑指Offer(第二版)面试题46:把数字翻译成字符串

题目要求:

给定一个数字,按照如下规则翻译成字符串:0翻译成“a”,1翻译成“b”…25翻译成“z”。一个数字有多种翻译可能,例如12258一共有5种,分别是bccfi,bwfi,bczi,mcfi,mzi。实现一个函数,用来计算一个数字有多少种不同的翻译方法。

解题思路:

下面我们从自上而下和自下而上两种角度分析这道题目,以12258为例:

自上而下,从最大的问题开始,递归 :
                     12258
                   /       \
              b+2258       m+258
              /   \         /   \
          bc+258 bw+58  mc+58  mz+8
          /  \      \        \     \
      bcc+58 bcz+8   bwf+8   mcf+8  mzi
        /        \       \     \
   bccf+8        bczi    bwfi   mcfi
     /
 bccfi
有很多子问题被多次计算,比如258被翻译成几种这个子问题就被计算了两次。

自下而上,动态规划,从最小的问题开始 :
f(r)表示以r为开始(r最小取0)到最右端所组成的数字能够翻译成字符串的种数。对于长度为n的数字,f(n)=0,f(n-1)=1,求f(0)。
递推公式为 f(r-2) = f(r-1)+g(r-2,r-1)*f(r);
其中,如果r-2,r-1能够翻译成字符,则g(r-2,r-1)=1,否则为0。
因此,对于12258:
f(5) = 0
f(4) = 1
f(3) = f(4)+0 = 1
f(2) = f(3)+f(4) = 2
f(1) = f(2)+f(3) = 3 
f(0) = f(1)+f(2) = 5

作者:ryderchan
链接:https://www.jianshu.com/p/80e1841909b7
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

C++代码

#include <iostream>
#include <string>

using namespace std;

int GetTranslationCount(int num);
int GetTranslationCount(const string& num);

int main()
{
    int num = 0;
    while(num != -1)
    {
        cout << "input a number "<<endl;
        cin >> num;
        int result = GetTranslationCount(num);
        cout << "result: " << result << endl;
    }
    return 0;
}

int GetTranslationCount(int num)
{
    if(num < 0)
        return -1;
    string strNum = to_string(num);
    int result = GetTranslationCount(strNum);
    return result;
}

int GetTranslationCount(const string& num)
{
    int length = num.size();
    int* counts = new int[length];
    int count = 0;
    for(int i = length - 1; i >= 0; --i)
    {
        if(i < length - 1)
            count = counts[i+1];
        else
            count = 1;

        if(i < length - 1)
        {
            int digit1 = num[i] - '0';
            int digit2 = num[i+1] - '0';
            int twoNum = digit1 * 10 + digit2;
            if(twoNum <= 25 && twoNum >= 10)
            {
                if(i < length - 2)
                    count += counts[i+2];
                else
                    count += 1;
            }
        }

        counts[i] = count;
    }
    count = counts[0];
    delete[] counts;
    return count;
}

参考文献

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值