题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
#include<bits/stdc++.h>
using namespace std;
// 只需对需求的前两种比较
bool compare(pair<int, char> a, pair<int,char> b){ // 排序代码参考了评论区大佬,主要是pair的思想学到了
if(tolower(a.second) == tolower(b.second)) return a.first<b.first; // 反过来,先比较输入次序(需求2)
else return tolower(a.second) < tolower(b.second); // 余下一种情况比较字母序(需求1)
}
int main(){
string s;
while(getline(cin,s)){
vector<pair<int,char>> v;
char punct[1001] = {0};
for(int i=0;i<s.length();i++){
if(!isalpha(s[i]))
punct[i] = s[i]; // 插桩,把非字母的char位置固定下来
else v.push_back(make_pair(i,s[i])); // 打包‘下标’与‘值’,方便在compare中比较
}
sort(v.begin(),v.end(),compare);
int cot = 0;
for(int i=0;i<s.length();i++){
if(punct[i]>0){
cout<<char(punct[i]);
cot++; // v中存的纯字母,待会顺序遍历v需要用i减这个cot
continue;
}
cout<<char(v[i-cot].second); // 由于punct与v是一起遍历,所以顺序遍历v需要减错位
}
cout<<endl;
}
}
查看14道真题和解析