题目描述:
Given a string which contains only letters. Sort it by lower case first and upper case second.
It's NOT necessary to keep the original order of lower-case letters and upper case letters.
Have you met this question in a real interview? Yes ExampleFor "abAcD", a reasonable answer is "acbAD"
ChallengeDo it in one-pass and in-place.
题目思路:就用two pointers的方法,用l指针始终指向lower case letters,用r指针始终指向upper case letters。当l<r并且l指向了upper case,r指向了lower case的时候,就swap两个char。
Mycode(AC = 16ms):
class Solution { public: /** * @param chars: The letters array you should sort. */ void sortLetters(string &letters) { // write your code here int l = 0, r = letters.length() - 1; while (l < r) { while (l < r && lowercase(letters[l])) { l++; } while (l < r && !lowercase(letters[r])) { r--; } if (l >= r) break; swap(letters, l, r); } } bool lowercase(char ch) { return ch >= 'a' && ch <= 'z'; } void swap(string &letters, int i, int j) { char ch = letters[i]; letters[i] = letters[j]; letters[j] = ch; } };