将各个字母的输入顺序存储到数组/C++

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

#include<iostream>
#include<string>
#include<sstream>
#include<vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

char to_upper(char c){ //统一转换成大写
    if(c>= 'A' && c <='Z')
        return c;
    else
        return  c-32;
}
//
string transfer(string &str){
    vector<vector<char>> vec(26); //对应26个字母,每个字母的顺序记录在vec的相应位置上
    vector<char> seq; //将vec线性化
    string ans;

    // 按输入顺序取出所有字母
    for(char c: str){
        if(isalpha(c)){
            vec[to_upper(c) - 'A'].push_back(c);
        }
    }
    // 拍扁
    for(int i = 0; i <26; i++){
        for(int j = 0; j < vec[i].size(); j++)
            seq.push_back(vec[i][j]);
    }

//    for(int i = 0; i <seq.size(); i++)
//        cout<<seq[i]<<endl;
    int p=0;

    for(char c: str){
        if(isalpha(c)){
            ans+=seq[p];
            p++;
        }else
            ans+=c;
    }

    return ans;

}

int main(){
    string str;
    getline(cin, str);

    cout<< transfer(str)<<endl;

    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务