LeetCode/solutions/20. Valid Parentheses.md
2019-09-13 23:08:41 +08:00

31 lines
1.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
# 思路
用一个栈来存放左括号每次遇到左括号就将其入栈遇到右括号就查看是否与栈顶元素配对若能配对则pop栈顶元素继续下一循环否则返回false。
退出循环后若栈不空说明还剩下未配对的左括号则应该返回false。
时间复杂度O(n), 空间复杂度O(n)
# C++
``` 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) {
stack<char>stk;
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;
}
};
```