1. 程式人生 > 實用技巧 >Stack 類的應用(判斷有效的括號)

Stack 類的應用(判斷有效的括號)

棧是Vector的一個子類,它實現了一個標準的後進先出的棧。

這是一道LeetCode的簡單演算法題。

給定一個只包括'('')''{''}''['']'的字串,判斷字串是否有效。

有效字串需滿足:

  1. 左括號必須用相同型別的右括號閉合。
  2. 左括號必須以正確的順序閉合。

注意空字串可被認為是有效字串。

輸入: "()[]{}"
輸出: true
輸入: "([)]"
輸出: false

import java.util.HashMap;
import java.util.Stack;

class Solution {

	public static void main(String[] args) {
		Solution solution = new Solution();
		System.out.println(solution.isValid("({})"));
	}

	private HashMap<Character, Character> mappings;

	public Solution() {
		this.mappings = new HashMap<Character, Character>();
		this.mappings.put(')', '(');
		this.mappings.put('}', '{');
		this.mappings.put(']', '[');
	}

	public boolean isValid(String s) {
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (this.mappings.containsKey(c)) {
				char topElement = stack.empty() ? '#' : stack.pop();
				if (topElement != this.mappings.get(c)) {
					return false;
				}
			} else {
				stack.push(c);
			}
		}
		return stack.isEmpty();
	}
}