Reverse a string
March 13, 2019
Find kth largest element in running stream of numbers
December 26, 2019

Reverse only the alphabets in a string

Given a string that has alphabets and special characters. Write code that reverse only the alphabets in the string and does not change the special characters.

INPUT STRING: AB$C^%DEF*
OUTPUT: FE$D^%CBA*

We have discussed a simple code to reverse a string in this post. We use the same logic here, the only difference here is that we will ignore the special characters. Below is the code

bool isChar(char ch)
{
  return (ch >= 'a' && ch<='z') || (ch >= 'A' && ch<='z');
}
void reverse(char* str, int n)
{
  if(str == NULL || n <= 1)
    return;
  int low = 0;
  int high = n-1;
  while(low < high)
  {
    if(!isChar(str[low]))
      low++;
    else if(!isChar(str[high]))
      high--;
    else
    {
      char temp = str[low];
      str[low] = str[high];
      str[high] = temp;
      low++;
      high--;
    }
  }
}

The code traverse the string only once and takes O(n) time.

Leave a Reply

Your email address will not be published. Required fields are marked *