1. 程式人生 > >棧應用--符號匹配

棧應用--符號匹配

    幾年前學的資料結構,現在差不多快忘了,現在複習下。基礎字元棧程式碼

public class StringStack {
	
	private int maxSize;
	private String[] stackArray;
	private int top;
	
	public StringStack(int maxSize){
		this.maxSize = maxSize;
		stackArray = new String[maxSize];	//初始化陣列
		top = -1;	//初始化棧頂指標為-1
	}
	
	public void push(String i) throws Exception{
		if(isFull()){
			throw new Exception("棧已經滿了");
		}
		top = top+1;
		stackArray[top] = i;
	}
	
	public String peek(){
		return stackArray[top];
	}
	
	public String pop() throws Exception{
		if(isEmpty()){
			throw new Exception("棧為空");
		}
		String pelement = stackArray[top];		//待出棧的元素
		top = top - 1;
		return pelement;
	}
	
	public int getStackSize(){
		return top + 1;
	}
	public boolean isFull(){
		if(top == maxSize -1){
			return true;
		}
		return false;
	}
	public boolean isEmpty(){
		if(top == -1){
			return true;
		}
		return false;
	}

}

棧符號匹配程式碼 isMatch


public class MatchBracket {
	
	public static String[] leftBracket = {"(","[","{"};
	public static String[] rightBracket = {")","]","}"};
	
	
	public int pushLeft(StringStack stringStack, String bracket) throws Exception{
		for(int i=0; i < leftBracket.length; i++){
			if(leftBracket[i].equals(bracket)){
				stringStack.push(bracket);
				return i;
			}
		}
		return -1;
	}
	
	public boolean matchLeft(StringStack stringStack, String bracket) throws Exception{
		for(int i = 0; i < rightBracket.length; i++){
			if(rightBracket[i].equals(bracket)){
				//右邊符號數目大於左邊符號
				if(stringStack.isEmpty()){
					return false;
				}
				//檢視棧頂符號是否匹配左邊符號
				if(stringStack.peek().equals(leftBracket[i])){
					stringStack.pop();
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	public boolean isMatch(String inputStr, StringStack stack) throws Exception{
		char[] charArray = inputStr.toCharArray();
		for(char c : charArray){
			String bracket = String.valueOf(c);
			pushLeft(stack, bracket);
			boolean res = matchLeft(stack, bracket);
			if(!res){
				return false;
			}
		}
		if(stack.isEmpty()){
			return true;
		}else{
			return false;
		}
	}
	
	public static void main(String[] args) throws Exception {
		String machStr = "{a{b(c)}d}e";
		char[] charArray = machStr.toCharArray();
		StringStack stringStack = new StringStack(20);
		MatchBracket matchBracket = new MatchBracket();
		System.out.println(matchBracket.isMatch(machStr, stringStack));
	
	}

}