標籤:nts only color hat ring continue and tar contain
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn‘t contain \ or "
思路:
兩個標記,分別從前和從後往中間方向遍曆,遇到字母交換,否則遊標繼續往下走。
bool isLetter(char ch){ return ((ch >= ‘a‘ && ch <= ‘z‘) || (ch >= ‘A‘ && ch <= ‘Z‘));}string reverseOnlyLetters(string S){ string ret = S; int n = S.length(); int start = 0; int end = n - 1; while(start <= n-1 && end >= 0) { if(!isLetter(S[end])){end--;continue;} if(!isLetter(ret[start])){start++;continue;} ret[start++] = S[end--]; } return ret; }
[leetcode-917-Reverse Only Letters]