方法:双指针
class Solution {
public:
bool isletter(char ch)
{
if(ch>='a'&&ch<='z')
return true;
if(ch>='A'&&ch<='Z')
return true;
return false;
}
string reverseOnlyLetters(string s) {
int len=s.size();
int left=0,right=len-1;
string s1;
while(left<len)
{
if(isletter(s[left]))
{
while(!isletter(s[right]))
--right;
s1+=s[right];
++left;
--right;
}
else
{
s1+=s[left];
++left;
}
}
return s1;
}
};
2.
class Solution {
public:
bool isletter(char ch)
{
if(ch>='a'&&ch<='z')
return true;
if(ch>='A'&&ch<='Z')
return true;
return false;
}
string reverseOnlyLetters(string s) {
if(s.empty())
return s;
size_t left=0,right=s.size()-1;
while(left<right)
{
while(left<right&&!isletter(s[left]))
++left;
while(left<right&&!isletter(s[right]))
--right;
swap(s[left],s[right]);
++left;
--right;
}
return s;
}
};