腾讯2017秋招笔试编程题(一)

腾讯2017秋招笔试编程题(一)

时间限制:1秒
空间限制:32768K

假定一种编码的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把该编码按字典序排序,形成一个数组如下: a, aa, aaa, aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx, yyyy 其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。 编写一个函数,输入是任意一个编码,输出这个编码对应的Index.

输入描述:

输入一个待编码的字符串,字符串长度小于等于100.

输出描述:

输出这个编码的index

输入例子1:

baca

输出例子1:

16331

代码如下:

#include <iostream>
#include <string>
#include <unistd.h> 

using namespace std;

int get_string_index(const string &str)
{
    int index = -1;
    string temp;
    const char all_valid_char[] = {' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
                                    'o','p','q','r','s','t','u','v','w','x','y'};
    temp.resize(4);
    for(int i=1;i<26;++i){
        temp.at(0) = all_valid_char[i];
        for(int j=0;j<26;++j){
            temp.at(1) = all_valid_char[j];
            if( !j ){
                index++;
                temp.resize(1);
                if( temp == str ){
                    return index;
                }
                temp.resize(4);
                continue;
            }
            for(int m=0;m<26;++m){
                temp.at(2) = all_valid_char[m];
                if( !m ){
                    index++;
                    temp.resize(2);

                    if( temp == str ){
                        return index;
                    }
                    temp.resize(4);
                    continue;
                }
                for(int n=0;n<26;++n){
                    temp.at(3) = all_valid_char[n];
                    index++;
                    if( !n ){
                        temp.resize(3);
                    }
                    if( temp == str ){
                        return index;
                    }
                    if( temp.size() != 4 )
                        temp.resize(4);
                }
            }
        }
    }

    return 0;
}

int main()
{
    int index = get_string_index("baca");
    cout << " <<<<<<<<<<<<< index = " << index << " >>>>>>>>>>> " << endl;
    return 0;
}

执行结果如下:

<<<<<<<<<<<<< index = 16331 >>>>>>>>>>>

欢迎大家讨论!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值