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.
- Create a new string by alternately combining the characters of two halves of the string in reverse
- Add index to characters and reverse the string
- Reverse alternate k characters in a string
- Reverse Middle X Characters
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Min flips of continuous characters to make all characters same in a string
- Move all special char to the end of the String
- Count special palindromes in a String
- String with k distinct characters and no same characters adjacent
- Split numeric, alphabetic and special symbols from a String
- Check if a string can be rearranged to form special palindrome
- Minimal moves to form a string by adding characters or appending string itself
- Lexicographically smallest string formed by appending a character from the first K characters of a given string