leetcode 20:Valid Parentheses(15-10-8)

题目:

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.

思路:

这道题目和四则运算表达式求值比较类似,只需要用一个栈即可实现,具体方法为检测到左括号就入栈,检测到右括号就出栈,并将检测的右括号和出栈的左括号匹配,知道所有的都匹配时才为真。

时间复杂度:O(n)

实现:


class Solution {
public:
	bool isValid(string s) {
		if (s.size() < 2) return false;
		stack<char> myStack;
		for (int i = 0; s[i] != '\0'; i++)
		{
			if (s[i] == '(' || s[i] == '{' || s[i] == '[') myStack.push(s[i]);
			else if (myStack.empty()) return false;
			else
			{
				char temp = myStack.top();
				myStack.pop();
				if (temp + 1 == s[i] || temp + 2 == s[i]) continue;
				else return false;
			}
		}
		if (myStack.empty())       //A
			return true;
		return false;
	}
};

注意:A处

你可能感兴趣的:(leetcode 20:Valid Parentheses(15-10-8))