题解 | #字符串排序#
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;
}

查看15道真题和解析