Given a string which contains only letters. Sort it by lower case first and upper case second.
Example
Example 1:
Input: "abAcD"
Output: "acbAD"
Example 2:
Input: "ABC"
Output: "ABC"
Challenge
Do it in one-pass and in-place.
Notice
It's NOT necessary to keep the original order of lower-case letters and upper case letters.
Code (Java):1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class Solution { /* * @param chars: The letter array you should sort by Case * @return: nothing */ public void sortLetters( char [] chars) { if (chars == null || chars.length < 2 ) { return ; } int start = 0 ; int end = chars.length - 1 ; while (start <= end) { while (start <= end && Character.isLowerCase(chars[start])) { start++; } while (start <= end && Character.isUpperCase(chars[end])) { end--; } if (start <= end) { swap(chars, start, end); start++; end--; } } } private void swap( char [] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } } |
No comments:
Post a Comment