解题思路:
一道非常典型的双指针题目,定义两个指针从左右两边寻找字母,找到后交换,直到指针碰头或者到达边界,代码如下:
class Solution {
public:
string reverseOnlyLetters(string s) {
int n = s.size();
int left = 0, right = n - 1;
while(left < right) {
while(left < n && !isalpha(s[left])) {
left ++;
}
while(right >= 0 && !isalpha(s[right])) {
right --;
}
if(left < right) swap(s[left ++], s[right --]);
}
return s;
}
};