题目地址:https://leetcode-cn.com/problems/valid-parentheses/
思路:匹配到则弹出栈顶,元素也不放,否则把元素放到栈里
AC代码:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
if (stack.size() == 0) {
stack.push(a);
continue;
}
char peekChar = stack.peek();
if ((peekChar == '(' && a == ')') || (peekChar == '[' && a == ']') ||
(peekChar == '{' && a == '}')) {
stack.pop();
} else {
stack.push(a);
}
}
return stack.size() == 0 ? true : false;
}
}