leetCode https://leetcode.com/problems/valid-parentheses/
简单级别题目
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
分析题目大致可以得出这个是一个典型的栈结构
先进入的左边符号必定在最后遇到自己的右边符号,并且一旦遇到一个右边括号,就要进行出栈,如果出栈的符号与自己不匹配那么就不是合法字符。并且最后栈的长度一定为0;
class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
String a = s.substring(i, i + 1);
if (a.equals("(") || a.equals("[") || a.equals("{")) {
stack.push(a);
} else {
if (stack.size() > 0) {
if (a.equals(")") && !stack.pop().equals("(")) {
return false;
} else if (a.equals("}") && !stack.pop().equals("{")) {
return false;
} else if (a.equals("]") && !stack.pop().equals("[")) {
return false;
}
} else {
return false;
}
}
}
if (stack.size() > 0)
return false;
return true;
}
}