算法--排序--大小写字母数字分离(桶排序思想)
生活随笔
收集整理的這篇文章主要介紹了
算法--排序--大小写字母数字分离(桶排序思想)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目: 對D,a,F,B,c,A,z這個字符串進行排序,要求將其中所有小寫字母都排在大寫字母的前面,但小寫字母內部和大寫字母內部不要求有序。比如經過排序之后為a,c,z,D,F,B,A,這個如何來實現呢?如果字符串中存儲的不僅有大小寫字母,還有數字。要將小寫字母的放到前面,大寫字母放在中間,數字放在最后,不用排序算法,又該怎么解決呢?
思路:
桶排序參考:https://blog.csdn.net/qq_21201267/article/details/80993672#t10
/*** @description: 分離開大小寫字符,但不改變相對順序(桶排序思想)* @author: michael ming* @date: 2019/4/13 18:25* @modified by: */ #include <iostream> #include <time.h> using namespace std; void randomABCandNum(char *ch, size_t N) //生成隨機大小字母和數字 {char tempch[26+26+10];int i, j, k, randIndex;for(i = 0; i < 26; )tempch[i++] = 'A' + i;for(j=0; j < 26; j++)tempch[i++] = 'a' + j;for(k=0; k < 10; k++)tempch[i++] = '0' + k;srand((unsigned)time(NULL));for(int x = 0; x < N; ++x){randIndex = rand()%62;ch[x] = tempch[randIndex];cout << ch[x] << " ";}cout << endl; } void countseparate(char *ch, size_t N) {size_t lowerNum = 0, upNum = 0, digitNum = 0;for(int i = 0; i < N; ++i) //計數,看每種類型有多少個{if(ch[i] >= 'a' && ch[i] <= 'z')lowerNum++;else if(ch[i] >= 'A' && ch[i] <= 'Z')upNum++;elsedigitNum++;}size_t lowerIndex = 0, upIndex = lowerNum, digitIndex = lowerNum+upNum;//每種類型的起始下標int *temp = new int [N];for(int i = 0; i < N; ++i) //按區間寫入{if(ch[i] >= 'a' && ch[i] <= 'z')temp[lowerIndex++] = ch[i];else if(ch[i] >= 'A' && ch[i] <= 'Z')temp[upIndex++] = ch[i];elsetemp[digitIndex++] = ch[i];}for(int i = 0; i < N; ++i){ch[i] = temp[i]; //寫回原數組}delete [] temp;temp = NULL; } void printArr(char* arr, size_t N) //打印字符數組 {for(int i = 0; i < N; ++i){cout << arr[i] << " ";}cout << endl; } int main() {cout << "請輸入N,程序生成大小寫字母和數字的組合隨機序列:";size_t N;cin >> N;char ch[N];randomABCandNum(ch, N);cout << "程序現將字符按[小寫字母][大寫字母][數字]排列,內部順序不變:" << endl;countseparate(ch, N);printArr(ch, N); }總結
以上是生活随笔為你收集整理的算法--排序--大小写字母数字分离(桶排序思想)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php fpm 统计,php实现fpm开
- 下一篇: LeetCode 1008. 先序遍历构