剑指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

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;
}

参考文献

猜你喜欢

转载自blog.csdn.net/dongyu_1989/article/details/81059383