2014년 3월 28일 금요일

[자바스택응용]Stack을 응용한 문자열 뒤집기, 괄호체크 하기, [자바교육/자바강좌/자바교육잘하는곳/자바교육추천/자바실무교육/JAVA/JAVA교육/JAVA학원/JAVA실무교육]

[구로디지털자바스택응용]Stack을 응용한 문자열 뒤집기, 괄호체크 하기, [자바교육/자바강좌/자바교육잘하는곳/자바교육추천/자바실무교육/JAVA/JAVA교육/JAVA학원/JAVA실무교육]
 
 
 public class ArrayStack implements Stack   {           
             int top;         // current top of stack
             Object [] stack;   // element array
              
             public ArrayStack(int initialCapacity) {
                  if (initialCapacity < 1)
                  throw new IllegalArgumentException
                                        ("initialCapacity must be >= 1");
                  stack = new Object [initialCapacity] ;
                  top = -1;
             }
     
       public ArrayStack() {
      this(10);
       }
      
       public boolean isEmpty( ) {
          return top == -1;
       }      
       
        public Object peek() {
               if (isEmpty() )
                     throw new EmptyStackException();
               return stack[top];
        }    

       
  public void push(Object theElement) {
    // increase array size if necessary   
    if (top == stack.length - 1) ensureCapacity();
        
            // put theElement at the top of the stack 
            stack[++top] = theElement;
      }

 
     public Object pop() {
            if  (isEmpty())
                  throw new EmptyStackException();
            Object topElement = stack[top];
             stack[top--] = null;   // enable garbage collection
             return topElement;
      }   
   private void ensureCapacity()  {
      Object[] larger = new Object[stack.length*2];
      for (int index=0; index < stack.length; index++)
         larger[index] = stack[index];
      stack = larger;
   }
   public String toString() {
    if (isEmpty())
      return "<empty stack>";
    String result = "<stack :";
    for (int i = top; i >= 0; i--)
      result += stack[i] + " ";
    return result + ">";
  } // end toString
}
 
 
public class EmptyStackException extends RuntimeException {
   public EmptyStackException()   {
      super ("The stack is empty.");
   }
   public EmptyStackException (String message)   {
      super (message);
   }
}
 
//Stack을 응용한 문자열 뒤집기, 괄호체크 하기
public class StackApp {
  public static String reverseString (String str )    {
 //Create a new stack
 Stack stk = new ArrayStack();
 // push each character into stack
 for (int i = 0; i < str.length(); i++)  {
   char ch = str.charAt(i);
   stk.push( new Character(ch));
 } 
 String ret="";
    for (int i = 0; i < str.length(); i++) {
     char charFromStack = ((Character)stk.pop()).charValue();
        ret = ret + charFromStack;
    }
    return ret;
  }
  public static boolean bracketsBalance (String exp) {
    ArrayStack stk = new ArrayStack(exp.length() +1);
    for (int i = 0; i < exp.length(); i++) {
         //Scan across the __EXPRESSION__
         char ch = exp.charAt(i);
         if (  ch== '[' || ch == '('  )  {
            stk.push( new Character(ch));
         }        
   else if(ch == ']' || ch == ')')  { 
    //empty means brackets unmatched
   if (stk.isEmpty())   return false;
   char charFromStack = ((Character)stk.pop()).charValue();
   if (  ch == ']' && charFromStack != '['
     ||  (ch == ')' && charFromStack != '(')  )
     return false;
  } // end if
 } // end for loop
    return stk.isEmpty();  //empty means matched,  else unmatched
}
      
  public static void main(String args[]) {   
      if (args.length < 2)   {
    System.out.println("Usage : java StackApp String1 String2");
    System.exit(1);
      }
   String s1 = args[0];
   String s2 = args[1];
   System.out.println(s1 + " : " + reverseString(s1));
   if (bracketsBalance(s2))  {
    System.out.println("괄호가  정확함");
   }
   else {
    System.out.println("괄호가 부정확 함");
   }  
  }
}
 
 

댓글 없음:

댓글 쓰기