[LeetCode] Reverse Letters Then Special Characters in a String

3823. Reverse Letters Then Special Characters in a String

You are given a string s consisting of lowercase English letters and special characters.

Your task is to perform these in order:

  • Reverse the lowercase letters and place them back into the positions originally occupied by letters.
  • Reverse the special characters and place them back into the positions originally occupied by special characters.

Return the resulting string after performing the reversals.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string reverseByType(string s) {
vector<int> at[2];
for(int i = 0; i < s.length(); i++) {
at[isalpha(s[i]) ? 1 : 0].push_back(i);
}
for(auto& pos : at) {
for(int l = 0, r = pos.size() - 1; l < r; l++,r--) swap(s[pos[l]],s[pos[r]]);
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/reverse-letters-then-special-characters-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.