一.解法
https://leetcode-cn.com/problems/valid-parentheses/
要点:栈
Python,C++,Java用的方法相同,遍历字符串,对每个字符如果是左括号直接加入栈,如果是右括号则要取栈顶元素比较是否是匹配括号
二.Python实现
class Solution:
def isValid(self, s: str) -> bool:
stack = []
hashmap = {")": "(", "}": "{", "]": "["}
for char in s:
if char in hashmap:
top_element = stack.pop() if stack else '#'
if hashmap[char] != top_element:
return False
else:
stack.append(char)
return not stack
三.C++实现
class Solution {
public:
bool isValid(string s) {
stack<char> a;
if(s.length()==0) return true;
for(int i=0;i<s.length();i++){
if(a.empty()) a.push(s[i]);
else if(a.top()=='('&&s[i]==')') a.pop();
else if(a.top()=='['&&s[i]==']') a.pop();
else if(a.top()=='{'&&s[i]=='}') a.pop();
else a.push(s[i]);
}
return a.empty();
}
};
四.java实现
class Solution {
private HashMap<Character, Character> mappings;
public Solution() {
this.mappings = new HashMap<Character, Character>();
this.mappings.put(')', '(');
this.mappings.put('}', '{');
this.mappings.put(']', '[');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (this.mappings.containsKey(c)) {
char topElement = stack.empty() ? '#' : stack.pop();
if (topElement != this.mappings.get(c)) {
return false;
}
}
else {
stack.push(c);
}
}
return stack.isEmpty();
}
}