标签:
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.
解法:很简单的题目,使用stack即可。遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回false。
class Solution { public: bool isValid(string s) { int ss = s.size(); if(ss % 2 != 0) return false; stack<char> par; for (int i = 0; i < ss; i++) { switch (s[i]) { case ‘(‘: case ‘[‘: case ‘{‘: par.push(s[i]); break; case ‘)‘: if (par.empty() || par.top() != ‘(‘) return false; par.pop(); break; case ‘]‘: if (par.empty() || par.top() != ‘[‘) return false; par.pop(); break; case ‘}‘: if (par.empty() || par.top() != ‘{‘) return false; par.pop(); break; default: return false; } } return par.empty(); } };
[LeetCode]35. Valid Parentheses有效括号
标签:
原文地址:http://www.cnblogs.com/aprilcheny/p/4903837.html