HJ26 字符串排序 ●●

HJ26 字符串排序 ●●

描述

编写一个程序,将输入字符串中的字符按如下规则排序。

规则 1 :英文字母从 A 到 Z 排列,不区分大小写。

如,输入: Type 输出: epTy

规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。

如,输入: BabA 输出: aABb

规则 3 :非英文字母的其它字符保持原来的位置。

如,输入: By?e 输出: Be?y

数据范围:输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000

输入描述:

输入字符串

输出描述:

输出字符串

示例

输入:A Famous Saying: Much Ado About Nothing (2012/8).
输出:A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).

题解

1. 桶排序

统计26个字母的出现顺序,并进行遍历填充。
时间复杂度:O(n)
空间复杂度: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. 归并排序

归并排序思想,对非字母的位置进行判断跳过,
nlogn复杂度,需要额外空间,数据大时递归超时。

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_19887221/article/details/126626998