Reverse a string without affecting special characters


StringViews 11707

Given a string which contains special characters(such as %,&,*,^,$) and alphabets(‘a’ to ‘z’ and ‘A’ to ‘Z’), write a function that will reverse the string in a way that special characters are not affected

Example

INPUT
s = “a!@bc&d”

OUTPUT
“d!@cb&a”

Method 1(Simple Solution)

Algorithm

1. Create a auxilary string ‘t’ and store all the alphabetic characters in string ‘t’

2. Now, reverse the string ‘t’

3. Now, Traverse the input string and string ‘t’ at a time

a. If there is a alphabetic character in input string, then replace it with the character in string ‘t’
b. If the character in input string is not a alphabetic character, then just move to the next character

Method 2(Eficient Solution)

In this method we will be not using extra space

Algorithm

1. Traverse the input string with  two varaibles l and r where l =0 and r = n-1, n is the length of the input string

2.  while l < r

a. if s[l] is not a alphabet, then do l++
b. else if s[r] is not a alphabet, then do r–
c. else swap the characters in s[l] and s[r] and so l++, r–

#include<bits/stdc++.h>
using namespace std;
 
// Returns true if x is an aplhabatic character, false otherwise
bool isAlphabet(char x)
{
    return ( (x >= 'A' &&  x <= 'Z') ||
             (x >= 'a' &&  x <= 'z') );
}
 
void reverseString(char s[])
{
    // Initialize l and r
    int r = strlen(s) - 1, l = 0;
 
    //Till l meets r, travers from both ends
    while (l < r)
    {
        // ignore special characters
        if (!isAlphabet(s[l]))
            l++;
        else if(!isAlphabet(s[r]))
            r--;
 
        else // if both s[l] and s[r] are alphabatical characters
        {
            swap(s[l], s[r]);
            l++;
            r--;
        }
    }
}

int main()
{
    char s[] = "a!@bc&d";
    cout << "Input string: " << s << endl;
    reverseString(s);
    cout << "Output string: " << s << endl;
    return 0;
}

Try It

 

Translate »