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

相关推荐
fufu03111 分钟前
Linux环境下的C语言编程(四十一)
linux·c语言·算法
bing.shao7 分钟前
Golang 之闭包
java·算法·golang
顾子羡_Gu7 分钟前
算法进阶指南:搜索与数论基础
数据结构·算法
2301_7737303110 分钟前
数据结构—队列
数据结构
唯道行26 分钟前
计算机图形学·25 消隐2 区域子分算法-光线投射算法
人工智能·算法·计算机视觉·计算机图形学·opengl
测试人社区—小叶子27 分钟前
接口测试全攻略:从Swagger到MockServer
运维·c++·人工智能·测试工具·机器人·自动化·测试用例
jinxinyuuuus29 分钟前
FIRE之旅 财务计算器:实时交互式建模与前端性能工程
前端·人工智能·算法·自动化
千丈之松35 分钟前
能力和法律
算法
量子炒饭大师35 分钟前
Cyber骇客的脑机双链回流码 ——【初阶数据结构与算法】线性表之双向链表
数据结构·c++·链表
2401_8414956437 分钟前
【LeetCode刷题】缺失的第一个正数
数据结构·python·算法·leetcode·数组·哈希·缺失最小正整数