码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Sort Letters by Case

时间:2016-04-06 08:10:40      阅读:143      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!