`
huntfor
  • 浏览: 201293 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Valid Parentheses

 
阅读更多

新博文地址:[leetcode]Valid Parentheses

Valid Parentheses

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 boolean isValid(String s) {
		if((s.length() & 1) == 1){//这里为了提高效率,判断长度是否为偶数,删掉也无妨
			return false;
		}
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			char leftToken = s.charAt(i);
			if (leftToken == '(' || leftToken == '{' || leftToken == '[') {
				stack.push(leftToken);
			} else {
				switch (leftToken) {
					case ')':
						if (stack.isEmpty()|| stack.peek() != '(')
							return false;
						else stack.pop();break;
					case '}':
						if (stack.isEmpty() || stack.peek() != '{')
							return false;
						else stack.pop();break;
					case ']':
						if (stack.isEmpty() || stack.peek() != '[')
							return false;
						else stack.pop();break;
				}
			}
			if(i == s.length() - 1 && !stack.isEmpty()){//如果处理完毕,栈内还有元素,说明左括号太多了
				return false;
			}
		}
		return true;
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics