lintcode-medium-Sort Letters by Case

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

 

Notice

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

Example

For "abAcD", a reasonable answer is "acbAD"

Challenge

Do it in one-pass and in-place.

 

public class Solution {
    /** 
     *@param chars: The letter array you should sort by Case
     *@return: void
     */
    public void sortLetters(char[] chars) {
        //write your code here
        
        if(chars == null || chars.length == 0)
            return;
        
        int left = 0;
        int right = chars.length - 1;
        
        while(left < right){
            while(left < right && chars[left] >= 'a' && chars[left] <= 'z')
                left++;
            while(left < right && chars[right] >= 'A' && chars[right] <= 'Z')
                right--;
            
            if(left < right)
                swap(chars, left, right);
        }
        
        return;
    }
    
    public void swap(char[] chars, int i, int j){
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
        
        return;
    }
}

 

posted @ 2016-04-06 07:35  哥布林工程师  阅读(218)  评论(0编辑  收藏  举报