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
	}
}

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