首页 > 其他 > 详细

LeetCode 20 Valid Parentheses 括号匹配问题

时间:2015-05-05 10:33:51      阅读:268      评论:0      收藏:0      [点我收藏+]

题目:

Given a string containing just the characters ‘(‘‘)‘‘{‘‘}‘‘[‘ and ‘]‘, determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

翻译:

给一个字符串,判断括号是否匹配成功。


思路:

用一个字符栈,读到一个字符时判断,如果栈顶和当前这个字符是满足左右括号匹配,则弹出,否则压栈。

如果最后栈为空,说明匹配成功。 


代码:

 public static boolean isValid(String s) {
		if(s.length() == 0 )
			return true;
		Stack<Character> st = new Stack<Character>();
		st.push(s.charAt(0));
		for(int i = 1 ; i< s.length();i++)
		{
			if(!st.empty()&& ismatch(st.peek(), s.charAt(i)))//非空且栈顶和当前字符匹配,弹出
				st.pop();
			else {
				st.push(s.charAt(i));
			}
		}
		if(st.empty())
			return true;
		return false;
    }
	
	public  static  boolean ismatch(char a,char b)
	{
		if((a=='('&&b==')')||(a=='{'&&b=='}')||(a=='['&&b==']'))
			return true;
		else 
			return false;
	}


LeetCode 20 Valid Parentheses 括号匹配问题

原文:http://blog.csdn.net/vvaaiinn/article/details/45499035

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!