Reverse Only Letters
You are given a string, ‘S’. You need to reverse the string where characters that are not an alphabet stay in the same place, and the rest reverse their positions.
Eg: “a-bcd” becomes “d-cba”
The first line of the input contains ‘T’ denoting the number of test cases. The first line of each test case contains a string ‘S’.
For every test case, we need to print the reversed string in a new line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10 0 <= |S| <= 5000 Where |S| denotes the length of string 'S'. Time Limit: 1 Sec
Approach: Just like in order to reverse a string ‘S’ = “abcd”, we can can swap(S, S) and swap(S,S) to get new string “dcba”.
Similarly in this problem, we do the same using two pointers while ignoring the non-letter characters.
Eg: S = “a-bcd” we swap(S, S) and swap(S, S) to get the result.
- In the given string what we can do is maintain two variables one pointer to the 0th position and the other pointing to the ‘N - 1’ position.
- If both have letters we swap them and increment the first pointer and decrement second.
- Else if the first pointer has a non-letter we just increment it and if the second pointer has a non-letter we decrement it.
- We continue it till the first pointer is less than the second pointer.