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

原文地址:https://www.cnblogs.com/ranjiewen/p/8327703.html