Valid Parentheses

难度:3

个人总结:1Y能力太弱,考虑不周全,基本的数据结构使用不灵活

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>S;
		for(int i=0;i<s.size();i++)
		{
			if(s[i] == '(' || s[i] == '[' || s[i] == '{')	S.push(s[i]);
			else
			{
				if(S.empty())	return false;
				char ch=S.top();S.pop();
				if((ch == '(' && s[i] != ')') || (ch == '[' && s[i] != ']') || (ch == '{' && s[i] != '}'))
				{
					return false;
				}
			}
		}
		if(!S.empty())  return false;
		return true;
    }
};


你可能感兴趣的:(Valid Parentheses)