Given a string that has alphabets and special characters. Write code that
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.