标签:
package com.dy.xidian; import java.util.Stack; public class BracketMatch { public BracketMatch() { // TODO Auto-generated constructor stub } static final char[] dict = {‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘, ‘]‘}; public static void main(String[] args) { String str1 = "({[]})[]"; String str2 = "{([]}]"; if (match(str1)) System.out.println("合法"); else System.out.println("不合法"); if (match(str2)) System.out.println("合法"); else System.out.println("不合法"); } public static boolean match(String str) { Stack<Character> stack = new Stack<>(); stack.push(str.charAt(0)); for (int i = 1; i < str.length(); i++) { if (dict[location(stack.peek()) + 1] != stack.peek()) stack.push(str.charAt(i)); else stack.pop(); } if (stack.size() != 0) { return false; } else return true; } public static int location(char _c) { int i; for (i = 0; i < dict.length; i++) { if (dict[i] == _c) break; } if (i < dict.length) return i; else return -1; } }
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序任意,即([]())或者[([][])]等均为正确的表达式,[(])或([())均为不正确的格式。现在给一个表达式,判断其是否正确。
标签:
原文地址:http://www.cnblogs.com/xidongyu/p/5952169.html