Wednesday, June 29, 2016

Reverse an array without affecting special characters in Java

Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algo.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string, replace it with current character of temp[].

Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.

Solution 1:

public class ReverseArrayWithoutSpecial
{
   public static void main(String[] args)
   {
     System.out.println(reverseString("man ish#"));
   }
   public static String reverseString(String input)
   {
     char[] inputArr = input.toCharArray();
     char[] tempArr = new char[input.length()];
     int i=0;
     int j=0;
     for (char ch:inputArr)
     {
       if(Character.isAlphabetic(ch))
       {
         tempArr[i] = ch;
         i++;
       }
     }
     i--;
     while(j<i)
     {
       char temp = tempArr[i];
       tempArr[i]= tempArr[j];
       tempArr[j]=temp;
       j++;
       i--;
     }
     for(i=0,j=0;i<input.length();i++)
     {
       if(Character.isAlphabetic(inputArr[i]))
       {
         inputArr[i]= tempArr[j++];
       }
     }
     return new String(inputArr);
   }
 }

Result: hsi nam#


Solution 2:

public class ReverseArrayWithoutSpecial
{
   public static void main(String[] args)
   {
     System.out.println(reverseString("a,b$c"));
   }
   public static String reverseString(String input) {
    char[] inputArr = input.toCharArray();
    int l = 0;
    int r = inputArr.length - 1;
    while (l < r) {
      if (!Character.isAlphabetic(inputArr[l])) {
        l++;
      } else if (!Character.isAlphabetic(inputArr[r])) {
        r--;
      } else {
        char tempChar = inputArr[l];
        inputArr[l] = inputArr[r];
        inputArr[r] = tempChar;
        l++;
        r--;
      }
    }
    return new String(inputArr);
  }

 }

Result: c,b$a


No comments: