声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
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.
Brief
括号的匹配问题。
Input
(1)"()"
(2)"()[]{}"
Output
(1)true
(2)true
Explanation
Note that an empty string is also considered valid.
Ideas
栈问题,扫描每个字符串的时候,如果为前括号就放到栈中,如果为后括号,就比较栈顶元素是否匹配,如果匹配则出栈;不匹配返回false。
Code
class Solution {
public boolean isValid(String s) {
if (s.length() == 0) {
return true;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if (s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}') {
if (stack.size() == 0) {
return false;
}
if (s.charAt(i) == ')') {
if (stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
}
if (s.charAt(i) == ']') {
if (stack.peek() == '[') {
stack.pop();
} else {
return false;
}
}
if (s.charAt(i) == '}') {
if (stack.peek() == '{') {
stack.pop();
} else {
return false;
}
}
}
if (!stack.isEmpty()) {
return false;
}
return true;
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com