题解 | #字符串排序#

字符串排序

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

先把字母排好序,这里使用了 multiset,自定义了一下排序规则。

        vector<char> letter;
        for(int i=0;i<26;i++)
        {
            for(int j=0;j<str.length();j++)
            {
                if(str[j]-'a'==i||str[j]-'A'==i)
                    letter.push_back(str[j]);
            }
        }

与上面这种排序方式(26*N)相比,ms.insert的效率为log(n), n比较小时,还是会更好一些吧?

#include <iostream>
#include <set>

using namespace std;

struct alpha_cmp{
    bool operator() (const char& a, const char& b) {
        return tolower(a) < tolower(b);
    }
};

int main() {
    string str;
    while(getline(cin, str)) {
        multiset<char, alpha_cmp> ms;
        for (const auto& i:str) {
            if (isalpha(i)) ms.insert(i);
        }
        auto alpha = ms.begin();
        int k = 0;
        for (const auto& i:str) {
            if (!isalpha(i)) {
                cout << i;
            } else {
                cout << *alpha;
                alpha++;
            }
        }
        cout << endl;
    }
}
全部评论

相关推荐

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