题目的主要信息:

根据题意,把英语单词按照大小(ASCII码值从小到大)排列。

方法一:

用sort函数对str进行排序。

具体做法:

#include <iostream>
#include <string>
#include <algorithm>

using  namespace std;

int main(){
    string str;
    while(cin>>str)//可能有多组输入
    {
        sort(str.begin(),str.end());//排序
        cout<<str<<endl;
    }   
    return 0;
}

复杂度分析:

  • 时间复杂度:O(nlog2n)O(nlog_2n),sort排序用的快速排序。
  • 空间复杂度:O(1)O(1),只用了常数空间。

方法二:

通过查ASCII码表可知0-9,a-z,A-Z的ASCII码的范围是48-57,97-122,65-90,用一个大小为123的vector count来存储每个字符的个数。输出的时候遍历一遍count,即按照ASCII码大小遍历一遍,若当前ASCII码有字符则输出该字符,需要注意的是可能会有重复字符,因此需要重复输出至count为0。 alt

具体做法:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using  namespace std;

int main(){
    string str;
    vector<int> count(123,0);
    while(cin>>str)//可能有多组输入
    {
        for(int i=0;i<str.size();i++)
        {
            count[str[i]]++;//统计出现的次数
        }
        for(int i=0;i<count.size();i++)//按照ASCII码遍历
        {
            while(count[i]!=0)//需要重复输出
            {
                cout<<char(i);
                count[i]--;
            }
        }
        cout<<endl;
    }   
    return 0;
}

复杂度分析:

  • 时间复杂度:O(n)O(n),需要遍历一遍字符串。
  • 空间复杂度:O(1)O(1),只用了常数空间统计字符数量。