Thursday, April 18, 2019

Lintcode 49. Sort Letters by Case

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

Example

Example 1:
 Input:  "abAcD"
 Output:  "acbAD"

Example 2:
 Input: "ABC"
 Output:  "ABC"
 

Challenge

Do it in one-pass and in-place.

Notice

It's NOT necessary to keep the original order of lower-case letters and upper case letters.
Code (Java):

public class Solution {
    /*
     * @param chars: The letter array you should sort by Case
     * @return: nothing
     */
    public void sortLetters(char[] chars) {
        if (chars == null || chars.length < 2) {
            return;
        }
        
        int start = 0;
        int end = chars.length - 1;
        
        while (start <= end) {
            while (start <= end && Character.isLowerCase(chars[start])) {
                start++;
            }
            
            while (start <= end && Character.isUpperCase(chars[end])) {
                end--;
            }
            
            if (start <= end) {
                swap(chars, start, end);
                start++;
                end--;
            }
        }
    }
    
    private void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}

No comments:

Post a Comment