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’.
Output Format:
For every test case, we need to print the reversed string in a new line.
Note:
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
2
a-bcd
!s-cx
d-cba
!x-cs
In the first test case:
“a-bcd” after removing non-letter will be “abcd”.
Reversing “abcd” will get “dcba”.
Placing non-letters in the correct position in “dcba”, we get: “d-cba”.
In the second test case:
“!s-cx” after removing non-letter will be “scx”.
Reversing “scx” will get “xcs”.
Placing non-letters in the correct position in “xcs”, we get: “!x-cs”.
2
a-bC-dEf-ghIj
Qedo1ct-eeLg=ntse-T!
j-Ih-gfE-dCba
Test1ng-Leet=code-Q!
In the first test case:
“a-bC-dEf-ghIj” after removing non-letter will be “abCdEfghlj”.
Reversing “abCdEfghlj” will get “jlhgfEdCba”.
Placing non-letters in the correct position in “jlhgfEdCba”, we get: “j-Ih-gfE-dCba”.
In the second test case:
“!s-cx” after removing non-letter will be “Qedo1ct-eeLg=ntse-T!”.
Reversing “QedocteeLgntseT” will get “TestngLeetcodeQ”.
Placing non-letters in the correct position in “TestngLeetcodeQ”, we get: “Test1ng-Leet=code-Q!”.
Try to use variables to track the positions of last and first alphabets.
Approach: Just like in order to reverse a string ‘S’ = “abcd”, we can can swap(S[0], S[3]) and swap(S[1],S[2]) 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[0], S[4]) and swap(S[2], S[3]) to get the result.
Algorithm:
O(N), where ‘N’ is the length of the string.
We are only iterating in the string so, the time complexity is O(N).
O(1).
We are only using the original string and not creating a new string.