18711 字符串去重

思路

  1. **读取输入**:读取字符串的长度和字符串本身。

  2. **使用集合去重**:利用集合(`set`)去除字符串中的重复字母。

  3. **排序**:将集合中的字母按ASCII码从小到大排序。

  4. **输出结果**:将排序后的字母拼接成字符串并输出。

伪代码

```

function remove_duplicates_and_sort(n, s):

if n == 0:

return ""

create a set unique_chars

for each char in s:

add char to unique_chars

convert unique_chars to a list and sort it

join the sorted list into a string

return the resulting string

```

C++代码

cpp 复制代码
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

using namespace std;

string remove_duplicates_and_sort(int n, const string& s) {
    if (n == 0) {
        return "";
    }

    set<char> unique_chars(s.begin(), s.end());
    vector<char> sorted_chars(unique_chars.begin(), unique_chars.end());
    sort(sorted_chars.begin(), sorted_chars.end());

    return string(sorted_chars.begin(), sorted_chars.end());
}

int main() {
    int n;
    string s;
    cin >> n >> s;

    string result = remove_duplicates_and_sort(n, s);
    cout << result << endl;

    return 0;
}

总结

  1. **问题建模**:将字符串中的字母去重并排序。

  2. **算法选择**:使用集合去重,使用排序算法对集合中的字母进行排序。

  3. **实现细节**:利用集合和向量来存储和处理字母,最后将结果拼接成字符串输出。

  4. **边界条件**:处理字符串长度为0的情况,直接返回空字符串。

相关推荐
bIo7lyA8v1 小时前
算法稳定性分析中的输入扰动建模的技术9
算法
CoderCodingNo1 小时前
【GESP】C++三级真题 luogu-B4499, [GESP202603 三级] 二进制回文串
数据结构·c++·算法
sinat_286945191 小时前
AI Coding 时代的 TDD:从理念到工程落地
人工智能·深度学习·算法·tdd
炽烈小老头1 小时前
【 每天学习一点算法 2026/04/12】x 的平方根
学习·算法
ASKED_20191 小时前
从排序到生成:腾讯广告算法大赛 2025 baseline解读
人工智能·算法
田梓燊2 小时前
leetcode 160
算法·leetcode·职场和发展
_深海凉_2 小时前
LeetCode热题100-颜色分类
python·算法·leetcode
网安INF2 小时前
数据结构第三章:栈、队列和数组
数据结构
hetao17338372 小时前
2026-04-09~12 hetao1733837 的刷题记录
c++·算法
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 136. 只出现一次的数字 | C++ 哈希表&异或基础解法
c++·算法·leetcode