【问题标题】:How to get set of character of string in same order as in parent string in C++如何以与 C++ 中的父字符串相同的顺序获取字符串的字符集
【发布时间】:2020-11-22 05:58:18
【问题描述】:

我有一个字符串并想从中删除重复项,但我希望它以相同的顺序。 std::set or std::unordered_set 似乎没有帮助。我有任何 DS 还是必须手动解决这个问题?例子:- “ddbbccaa”应该是“dbca”。

【问题讨论】:

  • 输入"ddbbddaab"(存在不连续重复字符)应该返回什么?
  • 在这种情况下根据第一次出现“dba”
  • std:: unique?
  • DS 是什么意思?
  • @Alan Birtles 我的意思是数据结构 (DS)

标签: c++ string data-structures


【解决方案1】:
  1. 遍历输入字符串
  2. 在您之前没有见过字符时将字符添加到结果字符串中
#include <iostream>
#include <string>
#include <unordered_set>

std::string removeDuplicates(const std::string& str) {
    std::string result;
    std::unordered_set<char> seen;
    for (char c : str) {
        if (seen.find(c) == seen.end()) {
            result += c;
            seen.insert(c);
        }
    }
    return result;
}

int main(void) {
    std::cout << removeDuplicates("ddbbccaa") << '\n';
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    相关资源
    最近更新 更多