20. Valid Parentheses [LeetCode]

20Valid 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.

平衡符号判定问题,经典的栈应用问题(关于栈的应用还有几个经典场景:Postfix Expressions和Infix to Postfix Conversion ).

class Solution {
public:
	bool isValid(string s) {
		
		string left = "([{";
		string right = ")]}";

		stack<char> stk;

		for (auto c : s) {
			if (left.find(c) != string::npos) //means "until the end of the string"
			{
				stk.push(c);
			}
			else {
				if (stk.empty() || stk.top() != left[right.find(c)])
					return false;
				else
					stk.pop();
			}
		}
		return stk.empty();
	}
};

其他的一些思路:

Make an empty stack. 
Read characters until end of file. 
If the character is an opening symbol, push it onto the stack. 
If it is a closing symbol and the stack is empty, report an error. 
Otherwise, pop the stack. 
If the symbol popped is not the corresponding opening symbol, then report an error. 
At end of file, if the stack is not empty, report an error.

猜你喜欢

转载自blog.csdn.net/mc_007/article/details/80385645