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

LintCode-Sort Letters by Case

时间:2015-01-01 00:05:48      阅读:313      评论: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"

Solution:

 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         int len = chars.length;
 8         if (len <= 1) return;
 9 
10         int p1 = 0, p2 = len-1;
11         while (p1<len && chars[p1]>=‘a‘ && chars[p1]<=‘z‘) p1++;
12         while (p2>=0 && chars[p2]>=‘A‘ && chars[p2]<=‘Z‘) p2--;
13         while (p1<p2){
14             //swap p1 and p2.
15             char temp = chars[p1];
16             chars[p1] = chars[p2];
17             chars[p2] = temp;
18             //find next swap positions.
19             while (p1<len && chars[p1]>=‘a‘ && chars[p1]<=‘z‘) p1++;
20             while (p2>=0 && chars[p2]>=‘A‘ && chars[p2]<=‘Z‘) p2--;
21         }
22     }
23 }

 

LintCode-Sort Letters by Case

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4196831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!