首页 > 其他 > 详细

Lintcode: Sort Letters by Case

时间:2015-04-06 10:02:32      阅读:233      评论:0      收藏:0      [点我收藏+]
Given a string which contains only letters. Sort it by lower case first and upper case second.

Note
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.

Two Pointers:

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

Note
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.
 1 public class Solution {
 2     /** 
 3      *@param chars: The letter array you should sort by Case
 4      *@return: void
 5      */
 6     public void sortLetters(char[] chars) {
 7         //write your code here
 8         if (chars==null || chars.length==0) return;
 9         int l=0, r=chars.length-1;
10         while (true) {
11             while (l<r && isLower(chars, l)) {
12                 l++;
13             }
14             while (l<r && isUpper(chars, r)) {
15                 r--;
16             }
17             if (l == r) break;
18             swap(chars, l, r);
19         }
20     }
21     
22     public boolean isLower(char[] chars, int index) {
23         if (chars[index]>=‘a‘ && chars[index]<=‘z‘) return true;
24         else return false;
25     }
26     
27     public boolean isUpper(char[] chars, int index) {
28         if (chars[index]>=‘A‘ && chars[index]<=‘Z‘) return true;
29         else return false;
30     }
31     
32     public void swap(char[] chars, int l, int r) {
33         char temp = chars[l];
34         chars[l] = chars[r];
35         chars[r] = temp;
36     }
37 }

 

Lintcode: Sort Letters by Case

原文:http://www.cnblogs.com/EdwardLiu/p/4395474.html

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