leetcode Valid Parentheses

题目连接

https://leetcode.com/problems/valid-parentheses/ 

Valid Parentheses

Description

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. 

括号匹配。。

class Solution {
public:
	bool isValid(string s) {
		stack<char> A;
		size_t n = s.length();
		for (size_t i = 0; i < n; i++) {
			char &ch = s[i];
			if (ch == '(' || ch == '{' || ch == '[') {
				A.push(ch);
				continue;
			}
			if (ch == ')') {
				if (!A.size()) return false;
				if (A.top() == '(') A.pop();
				else A.push(ch);
			}
			if (ch == '}') {
				if (!A.size()) return false;
				if (A.top() == '{') A.pop();
				else A.push(ch);
			}
			if (ch == ']') {
				if (!A.size()) return false;
				if (A.top() == '[') A.pop();
				else A.push(ch);
			}
		}
		return !A.size();
	}
};
posted @ 2015-12-11 21:02  GadyPu  阅读(175)  评论(0编辑  收藏  举报