LeetCode 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.

分析与解答:

利用栈的原理,当遇到左边括号时将其进栈。遇到右边括号时,栈为空就输出false,接着判断栈顶元素是否与其相匹配,匹配就弹出栈顶元素。不匹配就输出false。其实string的长度是奇数就可以判断为false了。

class Solution {
public:
    bool isValid(string s) {
	int size = s.size();
	if (size == 0)
		return 1;
	if (size % 2)
		return 0;
	vector<char> v;
	v.clear();
	for (int i = 0; i < size; i++) {
		if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
			if (v.empty() || (s[i] == ')' && v.back() != '(')
					|| (s[i] == ']' && v.back() != '[')
					|| (s[i] == '}' && v.back() != '{')) {
				return 0;
			} else
				v.pop_back();
		} else {
			v.push_back(s[i]);
		}
	}
	return v.empty();
    }
};


你可能感兴趣的:(String,stack)