e641 - 10260 - Soundex
題目描述
題目要求實作 Soundex 編碼演算法,將輸入的單詞轉換為 Soundex code。Soundex 編碼將聽起來相似的單詞編碼為相同的數字序列,忽略 A、E、I、O、U、H、W、Y 等字母,並將相鄰的重複字母編碼為單一數字。
解題思路
程式碼直接根據題目描述的 Soundex 編碼表進行字串處理。對於輸入的每個單詞,程式碼遍歷字串中的每個字符,並根據其字母將其替換為對應的數字。如果遇到相鄰的相同字母,則只輸出一次數字。程式碼使用一個布林變數 x 來追蹤是否已輸出當前字母的編碼,以避免重複輸出。
複雜度分析
- 時間複雜度: O(n),其中 n 是輸入字串的長度。程式碼需要遍歷字串一次。
- 空間複雜度: O(1),程式碼只使用常數額外的空間。
程式碼
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
while(cin >> a){
int al=a.length();
bool x=0;
for(int i=0;i<al;i++){
if(a[i]=='B'||a[i]=='F'||a[i]=='P'||a[i]=='V'){
cout << '1';
x=1;
while(a[i]=='B'||a[i]=='F'||a[i]=='P'||a[i]=='V')
i++;
}
if(a[i]=='C'||a[i]=='G'||a[i]=='J'||a[i]=='K'||a[i]=='Q'||a[i]=='S'||a[i]=='X'||a[i]=='Z'){
cout << '2';
x=1;
while(a[i]=='C'||a[i]=='G'||a[i]=='J'||a[i]=='K'||a[i]=='Q'||a[i]=='S'||a[i]=='X'||a[i]=='Z')
i++;
}
if(a[i]=='D'||a[i]=='T'){
cout << '3';
x=1;
while(a[i]=='D'||a[i]=='T')
i++;
}
if(a[i]=='L'){
cout << '4';
x=1;
while(a[i]=='L')
i++;
}
if(a[i]=='M'||a[i]=='N'){
cout << '5';
x=1;
while(a[i]=='M'||a[i]=='N')
i++;
}
if(a[i]=='R'){
cout << '6';
x=1;
while(a[i]=='R')
i++;
}
if(x==1){
i--;
x=0;
}
}
cout << "\n";
}
}