Tuesday, May 12, 2015

[LintCode] Sort Letters by Case

Given a string which contains only letters. Sort it by lower case first and upper case second.
Example
For "abAcD", a reasonable answer is "acbAD"
Note
It's not necessary to keep the original order of lower-case letters and upper case letters.
Challenge
Do it in one-pass and in-place.

class Solution {
public:
    void sortLetters(string &letters) {
        // write your code here
        int len = letters.length();
        int cur = -1;
        for(int i=0;i<len;i++)
        {
            if(cur == -1)
            {
                if(islower(letters[i])) continue;
                cur = i;
            }
            else if(islower(letters[i]))
            {
               swap(letters[cur++], letters[i]);
            }
        }
    }
};