牛客網_華爲機試_034_圖片整理(字符排序)

題目描述

Lily上課時使用字母數字圖片教小朋友們學習英語單詞,每次都需要把這些圖片按照大小(ASCII碼值從小到大)排列收好。請大家給Lily幫忙,通過C語言解決。

 


輸入描述:

Lily使用的圖片包括"A"到"Z"、"a"到"z"、"0"到"9"。輸入字母或數字個數不超過1024。

輸出描述:

Lily的所有圖片按照從小到大的順序輸出

示例1

輸入

Ihave1nose2hands10fingers

輸出

0112Iaadeeefghhinnnorsssv

思路一:手擼字符快排壓壓驚,順便複習一下。注意容易錯誤的地方

#include <stdio.h>
#include <string.h>
//快排一次分組,返回劃分元下標
int QuickPartition(char *s, int low, int high)
{
	char value = s[low];    //取首元素作爲劃分元
	while (low < high)
	{
		while (low < high && s[high] >= value)    //low<high不可省略
			--high;
		if (low < high) s[low++] = s[high];
		while (low < high && s[low] <= value)
			++low;
		if (low < high) s[high--] = s[low];   //易錯
	}
	//劃分元置入正確位置
	s[low] = value;    //易錯易漏
	return low;
}

//快排
void QuickSort(char *s, int low, int high)
{
	if (low < high)    //易錯
	{
		int i = QuickPartition(s, low, high);
		QuickSort(s, low, i - 1);
		QuickSort(s, i + 1, high);
	}
}

int main()
{
	char str[1024];
	while (scanf("%s", str) != EOF)
	{
		int len = strlen(str);
		QuickSort(str, 0, len - 1);
		printf("%s\n", str);
	}
	return 0;
}


思路二:STL、泛型算法,沒技術含量

鏈接:https://www.nowcoder.com/questionTerminal/2de4127fda5e46858aa85d254af43941
來源:牛客網

#include <iostream>
#include <string>
#include <algorithm>
using  namespace std;
 
 
int main(){
    string data;
    while(cin>>data)
    {
        sort(data.begin(),data.end());
        cout<<data<<endl;
    }   
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章