From 55b2318fce5be9fbeb05e0b1c29878db1a10e2bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Fri, 5 Oct 2018 23:14:33 +0800 Subject: [PATCH] Create 20. Valid Parentheses.md --- 20. Valid Parentheses.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 20. Valid Parentheses.md diff --git a/20. Valid Parentheses.md b/20. Valid Parentheses.md new file mode 100644 index 0000000..24d7b42 --- /dev/null +++ b/20. Valid Parentheses.md @@ -0,0 +1,30 @@ +# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/) +# 思路 +用一个栈来存放左括号,每次遇到左括号就将其入栈,遇到右括号就查看是否与栈顶元素配对,若能配对则pop栈顶元素,继续下一循环,否则返回false。 +退出循环后,若栈不空,说明还剩下未配对的左括号,则应该返回false。 +时间复杂度O(n), 空间复杂度O(n) +# C++ +``` +class Solution { +private: + bool isLegal(const char& a, const char&b){ + if(a == '(' && b == ')') return true; + if(a == '[' && b == ']') return true; + if(a == '{' && b == '}') return true; + return false; + } +public: + bool isValid(string s) { + stackstk; + for(int i = 0; i < s.size(); i++){ + if(s[i] == ')' || s[i] == '}' || s[i] == ']'){ + if(stk.empty() || !isLegal(stk.top(), s[i])) return false; + stk.pop(); + } + else stk.push(s[i]); + } + if(!stk.empty()) return false; + return true; + } +}; +```