yipo
9/4/2017 - 4:50 PM

Soundex

Soundex

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

vector<char> gen_soundex_mapping()
{
    const map<size_t, string> table =
    {
        { 1, "BFPV" },
        { 2, "CGJKQSXZ" },
        { 3, "DT" },
        { 4, "L" },
        { 5, "MN" },
        { 6, "R" },
    };

    vector<char> mapping(128, '0');
    for (const auto &pair : table)
    {
        for (const auto ch : pair.second) mapping[ch] = '0' + pair.first;
    }
    return mapping;
}

string soundex(const string &str)
{
    static const auto mapping = gen_soundex_mapping();

    string code;
    char last, digit = '0';
    for (const auto ch : str)
    {
        last = digit, digit = mapping[ch];

        if (digit == '0' || digit == last) continue;
        code.push_back(digit);
    }
    return code;
}

int main()
{
    string str;
    while (getline(cin, str))
    {
        cout << soundex(str) << endl;
    }
    return 0;
}