2017校招真题 -腾讯-编码

题目描述

假定一种编码的编码范围是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

输出

复制
16331

思路:这道题并没有什么太简便的方法,就是一位一位找到比当前字符串小的字符串个数。
需要注意的就是当右侧没有字符时这个特殊情况,我先后写了两版代码:
第一版:
#include<iostream>
#include<string>

using namespace std;

int main(){
    string str;
    cin>>str;
    int s = str.size();
    if(s == 1){
        int res = 0;
        res += (str[0] - 'a')*25*25*25 + (str[0] - 'a')*25*25 + (str[0] - 'a')*25;
        res += str[0] - 'a';
        cout<<res;
    }else if(s == 2){
        int res = 0;
        res += (str[1] - 'a')*25*25 + (str[1] - 'a')*25;
        res += str[1] - 'a';
        res += (str[0] - 'a')*25*25*25 + (str[0] - 'a')*25*25 + (str[0] - 'a')*25;
        res += str[0] - 'a' + 1;
        cout<< res;
    }else if(s == 3){
        int res = 0;
        res += (str[2] - 'a')*25;
        res += str[2] - 'a';
        res += (str[1] - 'a')*25*25 + (str[1] - 'a')*25;
        res += str[1] - 'a' + 1;
        res += (str[0] - 'a')*25*25*25 + (str[0] - 'a')*25*25 + (str[0] - 'a')*25;
        res += str[0] - 'a' + 1;
        cout<< res;
    }else{
        int res = 0;
        res += str[3] - 'a';
        res += (str[2] - 'a')*25;
        res += str[2] - 'a' + 1;
        res += (str[1] - 'a')*25*25 + (str[1] - 'a')*25;
        res += str[1] - 'a' + 1;
        res += (str[0] - 'a')*25*25*25 + (str[0] - 'a')*25*25 + (str[0] - 'a')*25;
        res += str[0] - 'a' + 1;
        cout<< res;
    }
    return 0;
    
}

第二版:

#include<string>
#include<cmath>
#include<iostream>
#include<vector>
using namespace std;

int main(){
    string str;
    cin>>str;
    vector<char> v (str.begin(),str.end());
    v.resize(4,'!');
    int res = 0;
    for(int i = 0; i < 4 ; ++i){
        if(v[i] != '!'){
            for(int j = 1; j < 4-i; ++j)
                res += (v[i] - 'a') *pow(25,j);
            if(i+1 < 4 && v[i+1] != '!') res += v[i] - 'a' + 1;
            else res += v[i] - 'a';
        }
    }
    cout<<res;
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/J1ac/p/9644050.html