LintCode-Sort Letters by Case

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 }

 

posted @ 2014-12-31 23:32  LiBlog  阅读(500)  评论(0编辑  收藏  举报