HDU 1442(Soundex Indexing)

基础题,建立对照表,将每个字母对应指定的数字字符,按要求转换字符串即可,注意输出格式。

#include 
#include 
#include 
using namespace std;

map m; //字母-数字字符

//初始化对照表
void init()
{
    m['B'] = m['F'] = m['P'] = m['V'] = '1';
    m['C'] = m['G'] = m['J'] = m['K'] = m['Q'] = m['S'] = m['X'] = m['Z'] = '2';
    m['D'] = m['T'] = '3';
    m['L'] = '4';
    m['M'] = m['N'] = '5';
    m['R'] = '6';
    m['A'] = m['E'] = m['I'] = m['O'] = m['U'] = m['H'] = m['W'] = m['Y'] = 'X';
}

//将字符串s编码
string encode(const string& s)
{
    string r(s.substr(0, 1));

    for (int i = 1; s[i]; i++)
    {
        if (r.size() == 4)
            break;
        else if (m[s[i]] != 'X' && m[s[i]] != m[s[i - 1]])
            r += m[s[i]];
    }

    if (r.size() < 4)
        r += string(4 - r.size(), '0');

    return r;
}

int main()
{
    init();

    cout << string(9, ' ') << "NAME" << string(21, ' ') << "SOUNDEX CODE" << endl;
    string s;
    while (cin >> s)
        cout << string(9, ' ') << s << string(25 - s.size(), ' ') << encode(s) << endl;
    cout << string(19, ' ') << "END OF OUTPUT" << endl;
    return 0;
}

继续加油。

你可能感兴趣的:(HDU)