题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include <iostream>
#include <string>
using namespace std;
class String {
private:
string s;
public:
//构造函数
String(const string s) {
this->s.clear();
this->s = s;
return;
}
//析构函数
~String() {
this->s.clear();
return;
}
//打印(<<运算符重载)(友元函数)
friend ostream& operator<<(ostream& cout, String s) {
cout << s.s;
return cout;
}
//判断字符是否是字母
bool isLetter(const char ch)const {
if (('a' <= ch) && (ch <= 'z'))
return true;
if (('A' <= ch) && (ch <= 'Z'))
return true;
return false;
}
//将字符转化为数字,以便排序
int conversion(const char ch)const {
switch (ch) {
case 'a':
case 'A':
return 1;
case 'b':
case 'B':
return 2;
case 'c':
case 'C':
return 3;
case 'd':
case 'D':
return 4;
case 'e':
case 'E':
return 5;
case 'f':
case 'F':
return 6;
case 'g':
case 'G':
return 7;
case 'h':
case 'H':
return 8;
case 'i':
case 'I':
return 9;
case 'j':
case 'J':
return 10;
case 'k':
case 'K':
return 11;
case 'l':
case 'L':
return 12;
case 'm':
case 'M':
return 13;
case 'n':
case 'N':
return 14;
case 'o':
case 'O':
return 15;
case 'p':
case 'P':
return 16;
case 'q':
case 'Q':
return 17;
case 'r':
case 'R':
return 18;
case 's':
case 'S':
return 19;
case 't':
case 'T':
return 20;
case 'u':
case 'U':
return 21;
case 'v':
case 'V':
return 22;
case 'w':
case 'W':
return 23;
case 'x':
case 'X':
return 24;
case 'y':
case 'Y':
return 25;
case 'z':
case 'Z':
return 26;
default:
return 0;
}
}
//判断排序是否正确
bool judge(void)const {
//将a初值设为最小字母以顺利进入循环
char a = 'a', b = 0;
//遍历字符串
for (int i = 0; i < this->s.size(); i++)
if (this->isLetter(this->s[i])) {
b = s[i];
if (this->conversion(a) > this->conversion(b))
return false;
a = b;
}
return true;
}
//排序
void sort(void) {
//如果已排好序,直接返回
if (this->judge())
return;
//遍历,对字母进行交换排序,为满足规则2,只交换相邻的两个字母(类似于冒泡排序)
for (int i = 0; i < this->s.size(); i++)
//寻找第一个字母
if (this->isLetter(this->s[i]))
//寻找第二个字母
for (int j = i + 1; j < this->s.size(); j++)
if (this->isLetter(this->s[j])) {
//交换
if (this->conversion(this->s[i]) > this->conversion(this->s[j])) {
char ch = this->s[j];
this->s[j] = this->s[i];
this->s[i] = ch;
if (this->judge())
return;
}
//将第二个字母的位置传给i,减少循环次数
i = j - 1;
break;
}
//如果排序未成功,继续排序
if (!this->judge())
this->sort();
return;
}
};
int main() {
string str;
while (getline(cin, str)) { // 注意 while 处理多个 case
String s(str);
s.sort();
cout << s << endl;
}
}
// 64 位输出请用 printf("%lld")
查看14道真题和解析