RUN
C C++ JAVA PYTHON SQL HTML CSS DSA Robotics AWS CODING INTERVIEW PREPARATION

Made with  & Code

# Reverse Only Alphabets Problem

Written By -

Reverse Only Alphabets Problem

Given: A string containing special characters (!,@,^,&,\$) and alphabets (‘a’ to ‘z’ and ‘A’ to ‘Z’). We have to reverse only the alphabets keeping the special symbols intact.

Input: [email protected]%gh,q

Output: [email protected]%hg,A

Explanation: Here we have to reverse characters in the array and ignore the special symbols. Only the position of characters will change and position of special symbols will be same.

### # Approach 1(Efficient)

In this method, we will be not using extra space.

Code:

``````#include <iostream>
#include <string.h>

//Function returns 1(true) if x is alphabet,0(false otherwise

int check_alpha(char z)

{

int flag = 0;

if ((z >= 'A' && z <= 'Z') || (z >= 'a' && z <= 'z'))

flag = 1;

else

flag = 0;

if (flag == 0)

return 0;

else

return 1;

}

//Function reverses a string

void revstring(char str[])

{

// Initializing x and y

int x = strlen(str) - 1, y = 0;

//Traversing from both ends, till x &y are equal

while (y < x)

{

// leave special characters

if (!check_alpha(str[y]))

y++;

else if (!check_alpha(str[x]))

x--;

else

// if both s[y] and s[x] are alphabatical characters

//swap the alphabets

{

char temp;

temp = str[y];

str[y] = str[x];

str[x] = temp;

y++;

x--;
}
}
}

int main()

{

char str[] = "[email protected]%gh&q";

std::cout << "Input string: " << str << std::endl;

revstring(str);

std::cout << "Output string: " << str << std::endl;

return 0;

}``````

### # Approach 2

In this approach, we have to use extra space by making a new array like pass[].

1) Create a auxilary character array like pass[].
2) Now copy alphabets from given array to pass[].
3) Reversing pass[] using string reversal.
4) We traverse input string and pass in a single loop. When a alphabet character occurs in input string, replace it with present character of pass[].

Related Posts:

Online Compilers