Wednesday, June 22, 2016

Print all the characters present in the given string only once in a reverse order. Time & Space complexity should not be more than O(N).

/*An array which contains the alternating elements (non-zero) of opposite sign is called as Alt array. 
Given an array, find the maximum length of an array which is alternate array. */

/* 
e.g. 
1)Given a string aabdceaaabbbcd 
the output should be - dcbae 
2)Sample String - aaaabbcddddccbbdaaeee 
Output - eadbc 
3)I/P - aaafffcccddaabbeeddhhhaaabbccddaaaa 
O/P - adcbhef 
*/
public class PrintOnceReversed{
 public static void main(String...q){
  System.out.println(printReverse("aabdceaaabbbcd")); //dcbae
  System.out.println(printReverse("aaafffcccddaabbeeddhhhaaabbccddaaaa")); //adcbhef
  System.out.println(printReverse("aaaabbcddddccbbdaaeee")); //eadbc 
 }
 
 static String printReverse(String str){
  str = new StringBuffer(str).reverse().toString();
  boolean charArr []= new boolean[255];
  String revStr = "";
  for(int i=0 ; i<charArr.length ; i++)
   charArr[i] = false;
  
  for(int i=0 ; i<str.length() ; i++)
  {
   if(!charArr[str.charAt(i)])
   {
    revStr = revStr + str.charAt(i);
    charArr[str.charAt(i)] = true;
   } 
  }

   return revStr;
 }
}

No comments:

Post a Comment