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

相关推荐
逐雨~8 小时前
9.8C++作业
开发语言·c++
luckys.one12 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|13 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师13 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo313 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC14 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
利刃大大15 小时前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车16 小时前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle16 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです16 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器