文字の大文字と小文字の並べ替え-LintCode

2335 ワード

アルファベットのみを含む文字列を指定し、小文字の順に並べ替えます.
小文字または大文字の間には、元の文字列の相対的な位置を維持する必要はありません.
サンプルは「abAcD」を与え、可能な答えは「acbAD」である.
挑戦はその場でスキャンして完了
構想
#ifndef C49_H
#define C49_H
#include
#include
using namespace std;
class Solution {
public:
    /*
    * @param chars: The letter array you should sort by Case
    * @return: nothing
    */
    void sortLetters(string &chars) {
        // write your code here
        if (chars.empty())
            return;
        int left = 0, right = chars.size() - 1;
        //    , chars[left]     ,chars[right]         ,  
        //      left right  
        while (left < right)
        {
            if (isupper(chars[left]))
            {
                if (isupper(chars[right]))
                    right--;
                else
                {
                    swap(chars[left], chars[right]);
                    left++;
                    right--;
                }
            }
            else
            {
                if (isupper(chars[right]))
                {
                    left++;
                    right--;
                }
                else
                    left++;
            }
        }
    }
};
#endif