首页 > 其他 > 详细

lintcode-medium-Sort Letters by Case

时间:2016-04-06 08:10:08      阅读:224      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

lintcode-medium-Sort Letters by Case

原文:http://www.cnblogs.com/goblinengineer/p/5357696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!