首页 > 其他 > 详细

leetcode Valid Parentheses

时间:2015-12-11 22:11:25      阅读:145      评论:0      收藏:0      [点我收藏+]

题目连接

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();
	}
};

leetcode Valid Parentheses

原文:http://www.cnblogs.com/GadyPu/p/5040222.html

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