Sort Letters by Cases

题目:

Given a string which contains only letters. Sort it by lower case first and upper case second.

It's NOT necessary to keep the original order of lower-case letters and upper case letters.

分析:

基本题目,注意实现无bug,就是记得swap之前要判断是否start <= end。

解法:

class Solution {
public:
    /** 
     * @param chars: The letters array you should sort.
     */
    void sortLetters(string &letters) {
        // write your code here
        if (letters.size() == 0) {
            return;
        }
        int start = 0;
        int end = letters.size() - 1;
        while (start <= end) {
            while (letters[start] >= 'a' && letters[start] <= 'z') {
                start++;
            }
            while (letters[end] >= 'A' && letters[end] <= 'Z') {
                end--;
            }
            if (start <= end) {
                swap(letters[start], letters[end]);
            }
        }
    }
};

results matching ""

    No results matching ""