在C++中刪除重復(fù)字符的一種方法是使用哈希表??梢允褂靡粋€(gè)數(shù)組或者一個(gè)標(biāo)準(zhǔn)庫(kù)中的unordered_set來(lái)實(shí)現(xiàn)哈希表。具體步驟如下:
以下是一個(gè)使用unordered_set的示例代碼:
#include <iostream>
#include <unordered_set>
#include <string>
std::string removeDuplicates(const std::string& str) {
std::string result;
std::unordered_set<char> uniqueChars;
for (char c : str) {
if (uniqueChars.find(c) == uniqueChars.end()) {
uniqueChars.insert(c);
result += c;
}
}
return result;
}
int main() {
std::string input = "abracadabra";
std::string result = removeDuplicates(input);
std::cout << result << std::endl; // 輸出 "abrcd"
return 0;
}
注意:這種方法會(huì)保留第一次出現(xiàn)的字符,刪除其余重復(fù)的字符。如果要保留最后一次出現(xiàn)的字符,可以將哈希表的類型改為std::unordered_map<char, int>
,將字符映射到它們?cè)谧址械乃饕恢?。在遍歷字符串時(shí),更新哈希表中字符的索引值。在最后,遍歷哈希表,將索引值最大的字符添加到結(jié)果字符串中。