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的情况,直接返回空字符串。

相关推荐
How_doyou_do1 分钟前
树状数组底层逻辑探讨 / 模版代码-P3374-P3368
数据结构·算法·树状数组
想睡hhh12 分钟前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
小鹿鹿啊21 分钟前
C语言编程--14.电话号码的字母组合
c语言·开发语言·算法
cloues break.23 分钟前
C++初阶----模板初阶
java·开发语言·c++
wwww.wwww44 分钟前
Qt软件开发-摄像头检测使用软件V1.1
开发语言·c++·qt
小O的算法实验室1 小时前
2024年ESWA SCI1区TOP:量子计算蜣螂算法QHDBO,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
C语言魔术师1 小时前
509. 斐波那契数
算法·动态规划
共享家95271 小时前
栈相关算法题解题思路与代码实现分享
c++·leetcode
Wendy_robot1 小时前
【前缀和计算和+哈希表查找次数】Leetcode 560. 和为 K 的子数组
c++·算法·leetcode
o独酌o1 小时前
算法习题-力扣446周赛题解
算法·leetcode