在C++中删除重复字符的一种方法是使用哈希表。可以使用一个数组或者一个标准库中的unordered_set来实现哈希表。具体步骤如下:
- 遍历字符串的每个字符。
- 检查当前字符是否已经在哈希表中存在。
- 如果当前字符不存在于哈希表中,将其加入哈希表,并将其添加到新的字符串中。
- 如果当前字符已经存在于哈希表中,说明是重复字符,跳过该字符。
- 最终得到的新字符串就是删除重复字符后的结果。
以下是一个使用unordered_set的示例代码:
#include
#include
#include
std::string removeDuplicates(const std::string& str) {
std::string result;
std::unordered_set 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;
}
注意:这种方法会保留第一次出现的字符,删除其余重复的字符。如果要保留最后一次出现的字符,可以将哈希表的类型改为std::unordered_map
,将字符映射到它们在字符串中的索引位置。在遍历字符串时,更新哈希表中字符的索引值。在最后,遍历哈希表,将索引值最大的字符添加到结果字符串中。