HJ26 String sorting ●●
describe
Write a program to sort the characters in the input string according to the following rules.
Rule 1: English letters are arranged from A to Z, case insensitive.
For example, input: Type output: epTy
Rule 2: When the upper and lower case of the same English letter exists at the same time, it will be arranged according to the input order.
For example, input: BabA output: aABb
Rule 3: Other characters that are not English letters remain in their original positions.
For example, input: By?e output: Be?y
Data range: the length of the input string satisfies 1 \le n \le 1000 \1≤n≤1000
Enter a description:
input string
Output description:
output string
example
Song:A Famous Saying: Much Ado About Nothing (2012/8).Song
:A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).
answer
1. Bucket sort
Count the order of appearance of 26 letters, and perform traversal filling.
Time complexity: O(n)
Space complexity: O(1)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isLetter(char ch){
return toupper(ch) <= 'Z' && toupper(ch) >= 'A';
}
void bucketSort(string& str){
vector<string> buckets(26, "");
for(char ch : str){
if(isLetter(ch)){
buckets[toupper(ch)-'A'].push_back(ch); // 对26个字母进行记录,有相对顺序
}
}
int str_idx = 0, buck_idx = 0, num_idx = 0;
while(str_idx < str.length()){
if(isLetter(str[str_idx])){
if(buck_idx < buckets[num_idx].size()){
// 填充当前字母
str[str_idx++] = buckets[num_idx][buck_idx++];
}else{
// 当前字母遍历填充完成,跳到下一个字母
buck_idx = 0;
++num_idx;
}
}else{
++str_idx; // 非字母位置,跳过
}
}
}
int main(){
string str;
getline(cin, str);
bucketSort(str);
cout << str;
return 0;
}
2. Merge sort
The idea of merge sorting is to judge and skip non-letter positions,
nlogn complexity requires additional space, and the recursion times out when the data is large.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isLetter(char ch){
return toupper(ch) <= 'Z' && toupper(ch) >= 'A';
}
void mergeSort(string& str, string& sorted, int start, int end){
if(start >= end) return;
int mid = start + (end - start) / 2;
mergeSort(str, sorted, start, mid);
mergeSort(str, sorted, mid+1, end);
int left = start, right = mid+1;
int idx = start;
while(idx <= end){
if(isLetter(str[left]) == false){
++left;
}else if(isLetter(str[right]) == false){
++right;
}else if(isLetter(str[idx]) == false){
++idx;
}else if(left > mid){
sorted[idx++] = str[right++];
}else if(right > end){
sorted[idx++] = str[left++];
}else if(toupper(str[left]) > toupper(str[right])){
sorted[idx++] = str[right++];
}else if(toupper(str[left]) < toupper(str[right])){
sorted[idx++] = str[left++];
}else{
sorted[idx++] = str[left++];
}
}
for(int i = start; i <= end; ++i) str[i] = sorted[i];
}
int main(){
string str;
getline(cin, str);
string sorted = str;
mergeSort(str, sorted, 0, str.length()-1);
cout << str;
return 0;
}