问题描述
- 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.
- Example :
Input: “()”
Output: true
Input: “()[]{}”
Output: true
Input: “(]”
Output: false
Input: “([)]”
Output: false
Input: “{[]}”
Output: true
问题分析
- 利用栈来匹配左右括号
- 方法1 : 如果当前字符是左括号则入栈,如果是右括号,若当前栈为空,返回false。否则检查当前弹栈元素是否能匹配,若不能,则返回false。若能,则继续检查下一字符。若检查完毕,栈为空说明全部匹配完成,否则,说明左括号比右括号多,返回false
- 方法2,若遇到左括号,则将它对应的右括号入栈,遇到右括号,若栈空,则为false.否则,进一步检查出栈元素是否等于当前右括号,若不等,则为false。若等,则继续检查下一字符。若检查完毕,栈为空说明全部匹配完成,否则,说明左括号比右括号多,返回false
代码实现
- 方法1:
public boolean isValid(String s) {
if (s == null) {
return true;
}
char[] chs = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < chs.length; i++) {
char ch = chs[i];
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
}else {
if (ch == ')') {
//注意判空,防止 ({}))
if (stack.isEmpty() || stack.pop() != '('){
return false;
}
}else if (ch == ']') {
if (stack.isEmpty() ||stack.pop() != '['){
return false;
}
}else if (ch == '}') {
if (stack.isEmpty() ||stack.pop() != '{'){
return false;
}
}else {
return false;
}
}
}
//防止左括号个数多于右括号这种情况 :((({}))
return stack.isEmpty();
}
- 方法2:
public boolean isValid(String s) {
if (s == null) {
return true;
}
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
switch (ch) {
case '(' : stack.push(')'); break;
case '[' : stack.push(']'); break;
case '{' : stack.push('}'); break;
case ')' :
case ']' :
case '}' :
if (stack.isEmpty() || stack.pop() != ch) {
return false;
}
}
}
return stack.isEmpty();
}