java 括號匹配

/*
 *括號匹配
 * 1.用棧實現,如果讀取字符爲左括號,入棧
 * 2.如果讀取字符爲右括號
 *   棧爲空,返回false
 *   棧不爲空,和棧頂比較,是否匹配,匹配出棧一次,不匹配返回false
 * 3.最後棧不爲空,返回false,棧爲空返回true
 */
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class BracketMatch {
	/*
	 * 功能描述
	 * @author peinishangrichu
	 * @date 2019/10/17
	 * @param st
	 * @return 是否匹配
	 */
	public static boolean isMatch(String str) {
		// 用map定義括號匹配關係
		Map<Character, Character> map = new HashMap<Character, Character>();
		map.put(')', '(');// map[key,value]
		map.put('}', '{');// map[key,value]
		map.put(']', '[');// map[key,value]

		int length = str.length();// 字符串長度
		LinkedList<Character> stack = new LinkedList<Character>();
		for (int i = 0; i < length; i++) {
			if (map.containsValue(str.charAt(i))) {// 如果爲左括號,入棧
				stack.push(str.charAt(i));
			}
			if (map.containsKey(str.charAt(i))) {// 如果爲右括號,判斷棧是否爲空
				if (stack.isEmpty()) {
					return false;
				} else if (stack.peek() == map.get(str.charAt(i))) {
					stack.pop();
				} else
					return false;
			}
		}

		if (stack.isEmpty()) {// 尋循環遍歷完成判斷棧是否爲空
			return true;
		} else
			return false;
	}

	public static void main(String[] args) {
		System.out.println(isMatch("{()[()]}"));// 情況1:true
		System.out.println(isMatch("({)}"));// 情況2:false
		System.out.println(isMatch("()))(("));// 情況3:false
		System.out.println(isMatch((4+1)*{[(3-2)+(3-1)*2]*(4+5)}"));// 情況4:true
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章