Fork me on GitHub

20. Valid Parentheses

20. 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.

解析

class Solution_20 {
public:
	bool isValid(string s) {
		if (s.size()<1)
		{
			return true;
		}
		stack<char> sta;
		for (int i = 0; i < s.size();i++)
		{
			if (s[i]=='('||s[i]=='['||s[i]=='{')
			{
				sta.push(s[i]); //入栈
			}else if ((s[i] == ')' || s[i] == ']' || s[i] == '}')&&sta.empty())
			{
				return false;
			}
			else if ((s[i] == ')'&&sta.top() == '(') || (s[i] == ']'&&sta.top() == '[') || (s[i] == '}'&&sta.top() == '{'))
			{
				sta.pop();
			}else 
			{
				return false;
			}
		}

		if (sta.empty())
		{
			return true;
		}
		else
		{
			return false;
		}
	}
};

posted @ 2018-01-22 09:59  ranjiewen  阅读(120)  评论(0编辑  收藏  举报