051201
题目
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!"
解题思路
第一反应,这道题和345. Reverse Vowels of a String一模一样呀,只是一个是元音字母交换,一个是字母交换。
第一种!
class Solution {
public:
string reverseOnlyLetters(string S) {
if(S.length()<=1) return S;
int head=0, tail=S.length()-1;
while(head<tail){
head = S.find_first_of("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm", head);
tail = S.find_last_of("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm", tail);
if (head < tail) swap(S[head++], S[tail--]);
}
return S;
}
};
第二种
class Solution {
public:
string reverseOnlyLetters(string S) {
if(S.length()<=1) return S;
int head=0, tail=S.length()-1;
while(head<tail){
while(head<tail && !isalpha(S[head])) head++;
while(head<tail && !isalpha(S[tail])) tail--;
swap(S[head++], S[tail--]);
}
return S;
}
};
原来是不是字母可以用isalpha这个函数,python和c++都有,学到了!