标签:
Given a string which contains only letters. Sort it by lower case first and upper case second.
Example
For "abAcD"
, a reasonable answer is "acbAD"
与将负数都放在前面,正数都放在后面的题目一样。
时间复杂度为O(n)
找到第一大写字母,记录其下标为i,则小写字母必定在i之后出现,在i之后找到第一个出现的小写字母j。交换i, j. 注意:i 到 j 之间的字母必定为大写。 依次进行即可。
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 if (chars == null || chars.length == 0) { 8 return; 9 } 10 int i = 0; 11 for (i = 0; i < chars.length; i++) { 12 if (chars[i] >= ‘A‘ && chars[i] <= ‘Z‘) { 13 break; 14 } 15 } 16 for (int j = i + 1; j < chars.length; j++) { 17 if (chars[j] >= ‘a‘ && chars[j] <= ‘z‘) { 18 char temp = chars[i]; 19 chars[i] = chars[j]; 20 chars[j] = temp; 21 i++; 22 } 23 } 24 return; 25 } 26 }
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5555031.html