括号匹配问题

括号匹配问题:

 

import java.util.Stack;

public class SymbolMatch {
	
	public boolean check(String str) {
		Stack<Character> s = new Stack<Character>();
		boolean match = true;
		for (int i = 0; i < str.length() && match; i++) {
			try {
				switch (str.charAt(i)) {
					case '(' : 
					case '[' :
					case '{' : s.push(str.charAt(i)); break;
					case ')' : if (s.pop() != '(') match = false; break;
					case ']' : if (s.pop() != '[') match = false; break;
					case '}' : if (s.pop() != '{') match = false; break;
				}
			} catch (Exception e) {
				match = false;
			}
		}
		if (match && !s.isEmpty())
			match = false;
		
		return match;
	}
	
	public static void main(String[] args) {
		SymbolMatch sm = new SymbolMatch();
		System.out.println("(: " + sm.check("("));
		System.out.println("a(bc[d])e{fd}: " + sm.check("a(bc[d])e{fd}"));
		System.out.println("a(bc]d: " + sm.check("a(bc]d"));
		System.out.println("a(b(c)d: " + sm.check("a(b(c)d"));
		System.out.println("a(b)c)d: " + sm.check("a(b)c)d"));
	}
}

你可能感兴趣的:(括号匹配)