アルゴリズム学習7----1つの文字列の中で最初に1回しか現れない文字を見つける
タイトル:1つの文字列に1回だけ表示される最初の文字を見つけます.abaccdeffが入力されるとbが出力される.
アルゴリズムの考え方:
このアルゴリズムの実装は、適切なデータ構造を選択し、マッピングテーブルというデータ構造を選択することである.
マッピングテーブルは単純に進化した「配列」ですが、「配列」の下付き文字は任意のタイプであってもよい
したがって、データ構造として文字と数値のマッピングテーブルを選択し、文字列の各文字をスキャンし、現在の文字がマッピングテーブルに存在しない場合はマッピングテーブルに追加し、その値を1に設定します.逆に、その値に対応する値に1を追加します.
アルゴリズムの擬似コード
C++実装
アルゴリズムの考え方:
このアルゴリズムの実装は、適切なデータ構造を選択し、マッピングテーブルというデータ構造を選択することである.
マッピングテーブルは単純に進化した「配列」ですが、「配列」の下付き文字は任意のタイプであってもよい
したがって、データ構造として文字と数値のマッピングテーブルを選択し、文字列の各文字をスキャンし、現在の文字がマッピングテーブルに存在しない場合はマッピングテーブルに追加し、その値を1に設定します.逆に、その値に対応する値に1を追加します.
アルゴリズムの擬似コード
create map<char, int>
//scan the string,
for i <- 1 to s.length
if char is already existed in the map
then add its count
else assign 1 to the map
for begin <- m.begin() to m.end()
if found first not repeating char
then return its char
C++実装
//find first char that appear once in the string
char FirstNotRepeatingChar(const string &s)
{
//create map<char, int>
map<char, int> m;
//scan the string
for(int i = 0; i != s.length(); ++i)
{
//if char is already existed in the map
if(m[s[i]])
{
//then add its count
++m[s[i]];
}
else
{
//else assign 1 to the map
m[s[i]] = 1;
}
}
//for begin <- m.begin() to m.end()
for(auto begin = m.begin(); begin != m.end(); ++begin)
{
//if found first not repeating char
if(begin->second == 1)
{
//then return its char
return begin->first;
}
}
}