题解 | #字符串排序#

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

采用冒泡算法,这是一个稳定的排序算法,需要注意,该算法把相邻的元素两两交换,但是由于题目中给出字符中有其他字符,需要跳过,因此最后的排序算法如下
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
void sort_str(string &str) {
  bool exchange = true;
  int sz = str.size();
  for (int i = 0; i < sz - 1 && exchange; i++) {
    exchange = false;
    int j = sz - 1;
    int k = j - 1;
    while (k >= i) {
        if(isalpha(str[k])){
          if (isalpha(str[j]) && tolower(str[k]) > tolower(str[j])) {
            swap(str[k], str[j]);
             exchange = true;
          }
          j = k;
        }
      k = k - 1;
    }
  }
}
int main() {
    string str;
    getline(cin,str);
    sort_str(str);
    cout<<str<<endl;
}


全部评论

相关推荐

06-23 18:25
沈阳大学 Java
HR已读不回,是我说话方式不对吗?
大白之主:你是串子吗? hr: 我们不招人了,把岗位挂着boss只是因为我闲得慌
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着接:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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