c++刪除重復(fù)字符的方法是什么

c++
小億
173
2023-11-07 20:25:04

在C++中刪除重復(fù)字符的一種方法是使用哈希表??梢允褂靡粋€(gè)數(shù)組或者一個(gè)標(biāo)準(zhǔn)庫(kù)中的unordered_set來(lái)實(shí)現(xiàn)哈希表。具體步驟如下:

  1. 遍歷字符串的每個(gè)字符。
  2. 檢查當(dāng)前字符是否已經(jīng)在哈希表中存在。
  3. 如果當(dāng)前字符不存在于哈希表中,將其加入哈希表,并將其添加到新的字符串中。
  4. 如果當(dāng)前字符已經(jīng)存在于哈希表中,說(shuō)明是重復(fù)字符,跳過(guò)該字符。
  5. 最終得到的新字符串就是刪除重復(fù)字符后的結(jié)果。

以下是一個(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é)果字符串中。

0