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

相关推荐
‎ദ്ദിᵔ.˛.ᵔ₎10 分钟前
双指针、滑动窗口、前缀和、二分查找 算法
算法
顾北顾23 分钟前
多头注意力机制
人工智能·深度学习·算法
H1785350909626 分钟前
SolidWorks_基于草图的实体特征20_特征错误排查
算法·3d建模·solidworks
hujinyuan2016038 分钟前
2025年12月中国电子学会青少年机器人技术等级考试试卷(二级) 真题+答案
人工智能·算法·机器人
玖玥拾1 小时前
C/C++ 基础笔记(十三)继承
c语言·c++·继承
bIo7lyA8v1 小时前
算法复杂度评估的实验统计方法与可视化的技术8
算法
李老师讲编程2 小时前
中国电子学会图形化2020.12月Scratch三级考级题
算法·scratch·信息学奥赛·图形化编程·scratch素材
ao-weilai2 小时前
C++:哈希表
c++·哈希算法·散列表
汉克老师2 小时前
GESP7级C++考试语法知识(二、指数函数(1、pow() 函数)
c++·指数函数·pow·gesp7级·精度误差
退休倒计时2 小时前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript