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.


模拟操作

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
using namespace std;

class Solution {
public:
	bool isValid(string s) {
		if (s.size() == 1)
		{
			return false;
		}
		stack<char>sta;
		char ch;
		for (auto iter = s.begin(); iter != s.end(); iter++)
		{
			ch = *iter;
			if (ch == '(' || ch == '{' || ch == '[')
			{
				sta.push(ch);
			}
			else
			{
				if (sta.size() == 0)
				{
					return false;
				}
				ch = sta.top();
				sta.pop();
				switch (*iter)
				{
				case ')':
					if (ch != '(')
					{
						return false;
					}
					break;
				case '}':
					if (ch != '{')
					{
						return false;
					}
					break;
				case ']':
					if (ch != '[')
					{
						return false;
					}
					break;
				}
			}
		}
		if (sta.size() != 0)
		{
			return false;
		}
		return true;
	}
};

int main()
{
	Solution s;
	cout << s.isValid("[[)") << endl;
	return 0;
}


posted @ 2016-11-06 00:25  N3verL4nd  阅读(134)  评论(0编辑  收藏  举报