[编程题]图片整理

Talk is cheap, show me the code.

一、问题描述

Lily上课时使用字母数字图片教小朋友们学习英语单词,每次都需要把这些图片按照大小(ASCII码值从小到大)排列收好。请大家给Lily帮忙,通过C语言解决。

输入描述:

Lily使用的图片包括”A”到”Z”、”a”到”z”、”0”到”9”。输入字母或数字个数不超过1024。

输出描述:

Lily的所有图片按照从小到大的顺序输出

输入例子:

Ihave1nose2hands10fingers

输出例子:

0112Iaadeeefghhinnnorsssv

二、问题分析

简单的排序问题,可以直接使用STL库中的排序函数,也可以子集实现一个排序函数。

解题方式1:

采用STL库的方式,这应该是最简单的解法了。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string s;
    while (cin >> s)
    {
        sort(s.begin(), s.end());
        cout << s << endl;
    }

    return 0;
}

解题方式2:

自己最开始拿到问题的解法。。。还把每个字符存了一次,纪念一下傻傻的自己。。。

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main()
{
    string s;
    while (cin >> s)
    {
        vector<char> vect;
        for (int i = 0; i < s.size(); i++)
        {
            vect.push_back(s[i]);
        }
        sort(vect.begin(), vect.end());
        for (vector<char>::iterator it = vect.begin(); it != vect.end(); ++it)
        {
            cout << *it;
        }
        cout << endl;
    }

    return 0;
}

解题方式3:

子集实现了快速排序,然后调用排序进行处理。

#include <iostream>
#include <string>
using namespace std;

void quickSort(string::iterator beg, string::iterator end)
{
    if (beg >= end - 1)
    {
        return;
    }
    string::iterator it1 = beg;
    string::iterator it2 = end - 1;
    char ch = *beg;
    while (it1 < it2)
    {
        while (*it2 >= ch)
        {
            it2--;
        }
        while (*it1 <= ch && it1 < it2)
        {
            it1++;
        }
        if (it1 < it2)
        {
            char temp = *it1;
            *it1 = *it2;
            *it2 = temp;
        }
    }
    if (it1 != beg)
    {
        *beg = *it1;
        *it1 = ch;
    }
    quickSort(beg, it1);
    quickSort(it1 + 1, end);
}

int main()
{
    string s;
    while (cin >> s)
    {
        quickSort(s.begin(), s.end());
        cout << s << endl;
    }

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