[編程題]圖片整理

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章