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

相关推荐
lwf006164几秒前
PNN (Product-based Neural Network) 学习日记
算法·机器学习
Tairitsu_H2 分钟前
C++:优先队列的模拟实现
开发语言·c++·stl·优先队列
ZPC82103 分钟前
YOLO-3D + 双目相机 (RGB + 深度 + 点云) → 3D 位置 + 抓取姿态
人工智能·算法·计算机视觉·机器人
ZPC82104 分钟前
YOLOv8-3D(3D 目标检测 + 6D 抓取姿态)
算法·机器人
lzh2004091911 分钟前
效率与安全并重:C++ 线程安全
linux·c++
Shan120515 分钟前
RAII妙用:使用标准库的包装器
开发语言·c++
bubiyoushang88818 分钟前
基于 TGLVM 算法的迁移学习分类系统
算法·分类·迁移学习
Hua-Jay20 分钟前
OpenCV联合C++/Qt 学习笔记(十八)----二维码检测及积分图像
c++·笔记·qt·opencv·学习
Rabitebla27 分钟前
深入理解 C++ STL:stack 和 queue 的底层原理与实现
c语言·开发语言·数据结构·c++·算法
通信仿真爱好者36 分钟前
【无标题】
人工智能·算法·机器学习