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.

#include <iostream>
#include <stack>
using namespace std;

//解题思路。使用栈。
//1.如果是左括号,则直接压入栈中。
//2.如果遇到右括号,首先查看栈中是否为空,如果是,则返回false,如果不是,取top的元素比较,匹配则pop出来,如果不匹配则返回false.
//3.匹配完,如果栈中还有元素,怎返回false.
bool isValid(string s)
{
	stack<char> charStack;
	int i = 0;

	while(i<s.length())
	{
		char c = s[i];
		if(c == '(' || c == '{' || c == '[')
		{
			charStack.push(c);
		}
		else
		{
			if(charStack.empty())
			{
				return false;
			}

			char top = charStack.top();
			switch(c)
			{
			case ')':
				if(top == '(')
				{
					charStack.pop();
				}
				else
				{
					return false;
				}
				break;
			case '}':
				if(top == '{')
				{
					charStack.pop();
				}
				else
				{
					return false;
				}
				break;
			case ']':
				if(top == '[')
				{
					charStack.pop();
				}
				else
				{
					return false;
				}
				break;
			}
		}
		i++;
	}

	if(!charStack.empty())
	{
		return false;
	}

	return true;
}

void main()
{
	string s = "{[()]}";
	bool b = isValid(s);
	printf("%s\n",b?"ture":"false");
}


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