`
eriol
  • 浏览: 400157 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

括号匹配问题

阅读更多

括号匹配问题:

 

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"));
	}
}
1
0
分享到:
评论
1 楼 adam_zs 2013-03-13  
谢谢分享!

相关推荐

Global site tag (gtag.js) - Google Analytics