標籤:java 棧 stack 自訂 符號匹配
棧是存放對象的一種特殊容器,在插入與刪除對象時,這種結構遵循後進先出( Last-in-first-out,LIFO)的原則。java本身是有內建Stack類包,為了達到學習目的已經更好深入瞭解stack棧,自己動手自建java stack類是個很好的學習開始:
自建Java Stack 類
Stack 類:
package com.stack;import java.util.ArrayList;import java.util.Arrays;/** * Stack Class * @author ganyee * */public class Stack { //Define capacity constant:CAPACITY private static final int CAPACITY = 1024; //Define capacity private static int capacity; //Define the top position of stack //top = -1 meaning that the stack empty private static int top = -1; //Basic Object class array Object[] array; //Initialize the capacity of stack public Stack() { this.capacity = CAPACITY; array = new Object[capacity]; } //Get the size of stack public int getSize(){ if(isEmpty()){ return 0; }else{ return top + 1; } } //Get whether stack is empty public boolean isEmpty(){ return (top < 0); } //Get the top element of stack public Object top() throws ExceptionStackEmpty{ if(isEmpty()){ throw new ExceptionStackEmpty("Stack is empty"); } return array[top]; } //Push element to stack public void push(Object element) throws ExceptionStackFull{ if(getSize()== CAPACITY){ throw new ExceptionStackFull("Stack is full"); } array[++ top] = element; } //Pop element from stack public Object pop() throws ExceptionStackEmpty{ if(isEmpty()){ throw new ExceptionStackEmpty("Stack is empty"); } return array[top --]; } //Get the all elements of stack public String getAllElements() throws ExceptionStackEmpty{ String[] arr = new String[top + 1]; if(!isEmpty()){ for(int i = 0;i < getSize();i ++){ arr[i] = (String)array[i]; } } return Arrays.toString(arr); }}
自訂ExceptionStackEmpty異常類(關於如何自訂異常類可以看相關部落格)
package com.stack;public class ExceptionStackEmpty extends Exception { //Constructor public ExceptionStackEmpty(){ } //Define myself exception construct with parameters public ExceptionStackEmpty(String string){ super(string); }}
自訂ExceptionStackFull異常類
package com.stack;public class ExceptionStackFull extends Exception { //Constructor public ExceptionStackFull(){ } //Define myself exception construct with parameters public ExceptionStackFull(String string){ super(string); }}
測試類別:
package com.stack;public class StackTest { public static void main(String[] args) { // TODO Auto-generated method stub Stack stack= new Stack(); System.out.println(stack.getSize()); System.out.println(stack.isEmpty()); try { stack.push(8); stack.push(3); stack.push(4); stack.push(7); stack.push(1); stack.push(8); stack.push(3); stack.push(4); stack.push(7); stack.push(1); System.out.println(stack.getSize()); System.out.println(stack.top()); System.out.println(stack.getAllElements()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } catch (ExceptionStackFull e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (ExceptionStackEmpty e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
測試結果:
0true101[8, 3, 4, 7, 1, 8, 3, 4, 7, 1]1743817438
棧的應用:符號匹配
下面,我們將藉助一個棧結構 S,通過對算術運算式自左向右的一遍掃描,檢查其中的括弧是
否匹配。
假設算術運算式為 X = “x0x1x2…xn-1”,其中 xi 可以是括弧、常數、變數名或者算術運算子。我
們依次檢查 X 中的各個符號,非括弧的符號都可以忽略。若遇到左括弧,則將其壓入棧 S 中;若遇到右括弧,則將棧頂符號彈出並與該右括弧對比。如果發現某對括弧不匹配,或者遇到右括弧時棧為空白,或者整個運算式掃描過後棧非空,都可以斷定括弧不匹配。
在按照以上規則掃描完所有字元後,若棧為空白,則說明括弧是匹配的。如果按照前面對棧的實現,每一 push()和 pop()操作都只需常數時間,因此對於長度為 n 的算術運算式,上述演算法需要運行 O(n)的時間。
該演算法的虛擬碼描述如 演算法二.1 所示:
package com.stack;public class MatchClass { public static boolean Match(String str) throws ExceptionStackFull, ExceptionStackEmpty{ Stack stack = new Stack(); str = str.replaceAll(" ",""); char s; for(int i = 0;i < str.length();i ++){ if(str.charAt(i) == ‘(‘ || str.charAt(i) == ‘{‘ || str.charAt(i) == ‘[‘) stack.push(str.charAt(i)); else{ if(stack.isEmpty()) return false; else{ s = str.charAt(i); switch(s){ case ‘)‘: if((Character)stack.pop() != ‘(‘) return false; break; case ‘}‘: if((Character)stack.pop() != ‘{‘) return false; break; case ‘]‘: if((Character)stack.pop() != ‘[‘) return false; break; } } } } if(stack.isEmpty()){ return true; }else{ return false; } }}
package com.stack;public class ParentMatch { public static void main(String[] args) { MatchClass match = new MatchClass(); //String str = "()({})"; //Match //String str = "()({}) {([()[]])}";//Match //String str = "([]{)";//Not match //String str = ")([()] {}";//Not match String str = "([())]{}";//Not match try { if(!match.Match(str)){ System.out.println(str + ": Not Macth"); }else{ System.out.println(str + ": Macth"); } } catch (ExceptionStackFull e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExceptionStackEmpty e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
測試結果:
()({}): Macth()({}) {([()[]])}: Macth([]{): Not Macth)([()] {}: Not Macth([())]{}: Not Macth
文章參考:資料結構與演算法( Java 描述)鄧俊輝 著
轉載請註明出處,謝謝!
http://blog.csdn.net/github_27609763/article/details/46420149
Java 自訂Stack棧類及應用