Reverse Only Letters
Problem
Given a string s
, reverse the string according to the following rules:
- All the characters that are not English letters remain in the same position.
- All the English letters (lowercase or uppercase) should be reversed.
Return s
after reversing it.
Constraints
1 <= s.length <= 100
s
consists of characters with ASCII values in the range[33, 122]
.s
does not contain'\"'
or'\\'
.
Solution
The problem Reverse Only Letters
can be solved using the technique from Reverse Vowels of a String, except this time we reverse English letters instead of vowels.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
string reverseOnlyLetters(string s)
{
int left = 0, right = s.length() - 1;
while (left < right)
{
if (!isalpha(s[left]))
left += 1;
else if (!isalpha(s[right]))
right -= 1;
else
swap(s[left++], s[right--]);
}
return s;
}
};