Showing posts with label How to reverse a String without special characters. Show all posts
Showing posts with label How to reverse a String without special characters. Show all posts

How to reverse a String without special characters

Interesting and interview question that need to reverse only alphanumeric's from a given string by leaving all other special characters at same index position. Need to write a program with time complexity of O(N/2).
How to reverse a String without special characters

Example:


str = "#ABCD1234qwerty@";
Output : *#ytrewq4321DCBA@


str = "Java$Discover";
Output : revo$csiDavaJ 


str = "A!@#$% ^&*()Z";

Output : Z!@#$% ^&*()A

Lets see the solution,

  • First lets take Ascii value of numerics and alphabets (including caps) which comes as 48 to 57 for numeric (0...9), then 65 to 90 for alphabet (A...Z) and 97 to 122 for alphabet (a...z).
  • Just compare first and last character of string and if its alphanumeric then swap else continue with other characters as same way. 
  • This makes sure we are swapping or reversing only alphanumeric and by leaving all other special characters @ same index position. 
Lets see simple Java code implementation for the same.


public class StringReverse {

 public static void main(String[] args) {

  String str = "A!@#$% ^&*()Z";

  System.out.println("Original String : "+str);

  str = new StringReverse().reverseString(str);

  System.out.println("Reversed String : "+str);
 }

 public String reverseString(String str) {

  char[] arr = str.toCharArray();

  for (int i = 0, j = str.length() - 1; i < j;) {

   if (alphaNumericCheck(arr[i]) && alphaNumericCheck(arr[j])) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
    i++;
    j--;
   } else if (!alphaNumericCheck(arr[i])) {
    i++;
   } else if (!alphaNumericCheck(arr[j])) {
    j--;
   }

  }
  return String.valueOf(arr);
 }

 public boolean alphaNumericCheck(char ch) {
  if ((ch >= 48 && ch <= 57) // Numeric 0 to 9
    || (ch >= 65 && ch <= 90) // Alphabet A to Z (caps)
    || (ch >= 97 && ch <= 122)) // Alphabet a to z
   return true;
  else
   return false;

 }
}

OUTPUT:


Original String : A!@#$% ^&*()Z
Reversed String : Z!@#$% ^&*()A