UVa 10260 – Soundex
Soundex encoding groups words that sound similar based on their spelling.
For example: "can" and "khawn," "con" and "gone."
Soundex encoding converts each word into a sequence of numbers, where each number represents a letter.
Below is the Soundex encoding table:
- 1:B、F、P、V
- 2:C、G、J、K、Q、S、X、Z
- 3:D、T
- 4:L
- 5:M、N
- 6:R
The letters "A, E, I, O, U, H, W, Y" are not represented in the Soundex encoding.
If letters with the same encoding appear adjacent to each other, they are represented by a single digit in the Soundex encoding.
Words with the same Soundex encoding are considered the same word.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF input: Each line of input contains a word, all in uppercase letters. The length of each word is less than 20 letters. | For each line, output the Soundex code of the word. |
KHAWN PFISTER BOBBY | 25 1236 11 |
Thought Process
Use a map to record the Soundex code corresponding to each character, and store them using character keys. This approach allows accumulating the answer using strings. Characters not present in the Soundex code do not need to be explicitly declared; they will default to 0 when the map is initialized.
For each character in the received string, if the Soundex code of the current character is not 0, you need to determine if this character is the first Soundex code encountered. You can declare a boolean variable outside the loop to track this. If it's the first Soundex code, initialize a string variable ans (defaulted to "") outside the loop and append Map[current_character] to it. Also, declare a variable last outside the loop to store the Soundex code of the last encountered character and set last to Map[current_character].
If it's not the first Soundex code, check if the current Soundex code matches last. If they don't match, append Map[current_character] to ans and update last to the new Soundex code Map[current_character].If the Soundex code is 0, it indicates that subsequent characters should be reassessed. Therefore, set last to '0' to handle this scenario.
Sample Code-ZeroJudge E641: Soundex
#include <iostream>
#include <map>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
map<char, char>MAP;
MAP['B'] = '1';
MAP['F'] = '1';
MAP['P'] = '1';
MAP['V'] = '1';
MAP['C'] = '2';
MAP['G'] = '2';
MAP['J'] = '2';
MAP['K'] = '2';
MAP['Q'] = '2';
MAP['S'] = '2';
MAP['X'] = '2';
MAP['Z'] = '2';
MAP['D'] = '3';
MAP['T'] = '3';
MAP['L'] = '4';
MAP['M'] = '5';
MAP['N'] = '5';
MAP['R'] = '6';
string str;
while (cin >> str) {
bool first = true;
string ans = "";
char last;
for (int i = 0; i<str.length(); i++) {
const char ch = str[i];
if (MAP[ch] != 0) {
if (first) {
first = false;
ans += MAP[ch];
last = MAP[ch];
}
else {
if (MAP[ch] != last) {
ans += MAP[ch];
last = MAP[ch];
}
}
}
else last = '0';
}
cout << ans << "\n";
}
}
//ZeroJudge E641
//Dr. SeanXD