import java.util.Stack;

public class HebFlip {
	
	public static boolean isLeftAlone(char c)
	{
		/*
		 * Here I check if the char is a-z, A-Z, 0-9, space or a pancuation mark
		 * if it is the function return true, else - return false.		 * 
		 */
		if((c>='a' && c<='z')||(c>='A' && c<='Z') || (c>='0' && c<='9')
				|| c==',' || c=='.'  || c== ' ')
			return true;
		return false;		
	}
	
	public static char turnSpacial(char c)
	{
		/*
		 * This function replace between special characters 
		 * It actually swap the direction of the mark
		 * i.e: { becomes }, ( becomes ) ans so on.
		 */
		char[] origin =		{'{','}','<','>','[',']','(',')','\\','/'};
		char[] transpose = 	{'}','{','>','<',']','[',')','(','/','\\'};
		
		for (int i=0; i<origin.length; i++)
			if (c==origin[i])
				return transpose[i];
		return c;		
	}
	
	public static String flipIt(String s)
	{
		/*
		 *  I used a stack in order to swap the directions, 
		 *  I use a second stack to handel english / numbers that
		 *  will be inserted into the first stack when the english substring will end		
		 */
		String t = "";
		char c;
		int i=0;
		Stack<Character> heb = new Stack<Character>();
		Stack<Character> temp = new Stack<Character>();
		while(i<s.length()-1) //passing on all the string charactesrs.
		{
			c = turnSpacial(s.charAt(i));
			if( isLeftAlone(c)&& isLeftAlone(s.charAt(i+1)))
					{ //checking if this cahr and the next one are spacial
						temp.push(c);
					}
			else if( isLeftAlone(c)) 
			{
				/*
				 * If the next char is not special, we pop the temp stack into
				 * the Hebrew Stack.
				 */
				temp.push(c);
				while(!temp.empty())
				{
					heb.push(temp.pop());
				}
			}
			else {
				heb.push(c);
			}
			i++;
		}
		
		/*
		 * The while above runs until 1 char before the end 
		 * now I check the last char and push it to the correct Stack  
		 */
		c = s.charAt(s.length()-1);
		if(isLeftAlone(c))
			temp.push(c);
		else
			heb.push(c);
		
		if (!temp.isEmpty()) //checkinf if the english stack is empty
			while(!temp.empty())
			{
				heb.push(temp.pop());
			}
		
		while(!heb.empty())
		{ //poping the Stack to a String
			t+=heb.pop();
		}				
		return t;		
	}
	
	
	public static void main(String[] args) {
		String s="הנה בדיקה של (טקסט 15) בעברית";
		System.out.println(flipIt(s));
	
	}

}

