题解 | #字符串排序#

字符串排序

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

#include <iostream>
#include <string>
using namespace std;
// 首先将所有的字母按照输入的顺序拿出另存
// 将全是字母的字符串用冒泡的方法排序
// 再双指针法将字符串赋值回来
int main() {
    string str;
    getline(cin,str);
    string temp;
    for(char ch:str){
        if((ch<='Z'&&ch>='A')||(ch<='z'&&ch>='a'))
            temp+=ch;
    }
    for(int i=0;i<temp.size()-1;++i){
        for(int j=1;j<temp.size()-i;++j){
            char c1=temp[j-1];
            char c2=temp[j];
            if(c1<='Z')
                c1+=32;
            if(c2<='Z')
                c2+=32;
            if(c1>c2){
                char t=temp[j-1];
                temp[j-1]=temp[j];
                temp[j]=t;
            }
        }
    }
    int j=0;
    for(int i=0,j=0;i<str.size();++i){
        if(!((str[i]<='Z'&&str[i]>='A')||(str[i]<='z'&&str[i]>='a')))
            continue;
        str[i]=temp[j];
        j++;
    }
    cout << str;
}
// 64 位输出请用 printf("%lld")

方法2

#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 从a到z,遍历26遍字符串,按顺序保存到数组
// 再赋值回来
int main() {
    string str;
    getline(cin,str);
    vector<char> table;
    for(int i=0;i<26;++i){
        for(int j=0;j<str.size();++j){
            if(str[j]-'a'==i||str[j]-'A'==i)
                table.push_back(str[j]);
        }
    }
    for(int i=0,j=0;i<str.size();++i){
        if((str[i]<='Z'&&str[i]>='A')||(str[i]<='z'&&str[i]>='a'))
            str[i]=table[j++];
    }
    cout << str;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

Java大菜狗:纯纯招黑奴,一天还不到两百那么多要求,还不迟到早退,以为啥啊,给一点工资做一堆活,还以不拖欠员工工资为荣,这是什么值得骄傲的事情吗,纯纯***公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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