[Geeks for Geeks] Special array reversal

Special array reversal

Given a string S, containing special characters and all the alphabets, reverse the string without

affecting the positions of the special characters.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
bool isAlpha(char ch) {
return islower(ch) or isupper(ch);
}
public:
string reverse(string str) {
int l = 0, r = str.length() - 1;
while(l < r) {
while(l < r and !isAlpha(str[l])) l++;
while(l < r and !isAlpha(str[r])) r--;
if(l < r)
swap(str[l++], str[r--]);
}
return str;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/special-array-reversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.