日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

计数排序的应用----排序字符串

發布時間:2023/12/10 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 计数排序的应用----排序字符串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

加qq1126137994 微信:liu1126137994 一起學習更多技術!!!

題目:
給你一個原始字符串,根據該字符串內每一個字符串出現的次數,按照ASCII碼遞增的排序重新調整輸出。

舉例:
eeefgghh
則每種字符出現的次數分別是:
(1).eee 3次
(2).f 1次
(3).gg 2次
(4).hhh 3次
重新輸出后的字符串如下:
efghegheh

編程實現上述功能:
提示:
(1)原始字符串中僅可能出現字符與數字
(2)注意區分字符的大小寫

思路:
不同的字符與數字出現的次數可能為多次,可以利用哈希表原理,生成一個大小為128的數組,數組里面對應的值的下標,代表原始字符串中出現的字符的ASCII碼的小,數組的值,代表相應字符串出現的次數。剛好打印數組的下標字符,打印一次,數組對應的值減1,直到減為0則說明出現多次的字符已經全部輸出完成!

#include <iostream> #include <string>using namespace std;//求數組(哈希表)中值出現次數最多的下標,用于循環多少次 int max_count(int count[], int n) {int max_count = 0;for (int i = 1; i < n; i++){if (count[i]>count[max_count]){max_count = i;}}return max_count; }int main() {char str[1000];char* p = str;gets(str);int count[128];for (int i = 0; i < 128; i++){count[i] = 0;}for (; *p != 0; p++){//求數組中對應下標(即字符串的字符的值)出現的次數count[*p]++;}int num = max_count(count,128);for (int i = 0; i < num; i++){for (int j = 0; j < 128; j++){if (count[j] != 0){printf("%c",j);count[j]--;}}}//getchar();return 0; }

或者:

#include <iostream> #include <string>using namespace std;int max_count(int count[], int n) {int max_count = 0;for (int i = 1; i < n; i++){if (count[i]>count[max_count]){max_count = i;}}return max_count; }int main() {string str;getline(cin,str,'\n');int len = str.size();int count[128];for (int i = 0; i < 128; i++){count[i] = 0;}for (int i=0; i<len; i++){count[str[i]]++;}int num = max_count(count,128);for (int i = 0; i < num; i++){for (int j = 0; j < 128; j++){if (count[j] != 0){printf("%c",j);count[j]--;}}}//getchar();return 0; }

總結

以上是生活随笔為你收集整理的计数排序的应用----排序字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。