Given a string, that contains special character together with alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string in a way that special characters are not affected.
Input: str = "a,b$c" Output: str = "c,b$a" Note that $ and , are not moved anywhere. Only subsequence "abc" is reversed Input: str = "Ab,c,de!$" Output: str = "ed,c,bA!$"
1) Create a temporary character array say temp.
2) Copy alphabetic characters from given array to temp.
3) Reverse temp using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string, replace it with current character of temp.
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.
1) Let input string be 'str' and length of string be 'n' 2) l = 0, r = n-1 3) While l is smaller than r, do following a) If str[l] is not an alphabetic character, do l++ b) Else If str[r] is not an alphabetic character, do r-- c) Else swap str[l] and str[r]
Below are implementations of above algorithm.
Input string: a!!!b.c.d,e'f,ghi Output string: i!!!h.g.f,e'd,cba
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Program to count vowels, consonant, digits and special characters in string.
- Reverse Middle X Characters
- Add index to characters and reverse the string
- Reverse alternate k characters in a string
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Sort an array where a subarray of a sorted array is in reverse order
- First string from the given array whose reverse is also present in the same array
- Perl | Reverse an array
- Reverse an array in groups of given size
- C Program to Reverse Array of Strings
- Sorting array with reverse around middle
- Reverse an array upto a given position
- Write a program to reverse an array or string
- Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
- Reverse an array without using subtract sign ‘-‘ anywhere in the code