leetcode之Valid Parentheses

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

代码:

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

bool isValid(string s) {

	int len = s.size();
	if (len == 0)return true;
	if (len % 2 != 0)return false;
	stack<char> cstack;
	map<char, char> m;
	m['('] = ')';
	m['{'] = '}';
	m['['] = ']';
	set<char> left = { '(','{','[' };
	if (!left.count(s[0]))return false;
	cstack.push(s[0]); char last = s[0];

	for (int i = 1; i < len; i++) {
		if (left.count(s[i])) {
			cstack.push(s[i]);
			last = s[i]; }
		else if (s[i] == m[last]) { 
			cstack.pop(); 
			if (cstack.size() == 0)last='0';
			else last = cstack.top(); }
		else return false;
	}

	if (cstack.size() != 0)return false;
	return true;
}
int  main() {
	string s = "()[]{}";
	bool m = isValid(s);
	cout << m << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/82911247
今日推荐