一个字符串排序

编写一个程序,将输入字符串中的字符按如下规则排序。

规则1:英文字母从A到Z排列,不区分大小写。

如,输入:Type输出:epTy

规则2:同一个英文字母的大小写同时存在时,按照输入顺序排列。

如,输入:BabA输出:aABb

规则3:非英文字母的其它字符保持原来的位置。

如,输入:By?e输出:Be?y


有没有大佬帮解答一哈~~~
#笔试题目#
全部评论
#include <iostream> #include <unordered_map> #include <vector> using namespace std; struct cmp {     bool operator() (char x, char y) {         if (x < 'a')    x += 'a'-'A';         if (y < 'a')    y += 'a'-'A';         return x < y;     } };   string my_sort(string input) {     string s;     unordered_map<char, vector<char>> m; //     for (char c : input) {         if ('a' <= c && c <= 'z')  {             s.push_back(c);             m[c].push_back(c);         }         if ('A' <= c && c <= 'Z') {             s.push_back(c+'a'-'A');             m[c+'a'-'A'].push_back(c);         }     }           sort(s.begin(), s.end(), cmp());     int index = 0, cursor = 0;     for (int i = 0; i < input.size(); i++) {         char c = input[i];         if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) {             if (index && s[index] != s[index-1])    cursor = 0;             input[i] = m[s[index++]][cursor++];         }     }     return input; } int main(int argc, char *argv[]) {     string s = "Type";     cout << my_sort(s) << endl;     s = "BabA";     cout << my_sort(s) << endl;     s = "By?e";     cout << my_sort(s) << endl;     return 0; } 亲测可以
点赞 回复
分享
发布于 2019-12-15 21:54

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务