原题链接:https://leetcode.com/problems/valid-parentheses/
1. 题目介绍
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 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
2. 解题思路
这样的括号匹配的题目,使用堆栈来解决的可能性非常大。设置一个堆栈,堆栈中只存放所有的左括号。
从头遍历字符串,如果遇到的字符是 ‘(’, ‘[’, ‘{’ 这三种左括号的话,就将它们存入堆栈。
如果遇到 ‘)’, ‘]’ ,’}’ 这三种右括号。就需要把当前的字符和堆栈顶部的左括号进行比对,如果右括号和栈顶左括号匹配的话,就弹出栈顶元素;否则就返回 false。
如果所有的括号都被匹配了,那么堆栈将变为空。如果遍历完字符串后,堆栈还没有空,那就是左括号多了,同样返回false。
实现代码
class Solution {
public boolean isValid(String s) {
int length = s.length();
Stack<Character> sta = new Stack<Character>();
for (int i = 0; i<length ; i++) {
char a = s.charAt(i);
if (a == '(' || a == '[' || a == '{') {
sta.push(a);
}else {
if(sta.empty() == true){
return false;
}
char b = sta.peek();
if (a == ')' && b == '(') {
sta.pop();
}else if (a == ']' && b == '[') {
sta.pop();
}else if (a == '}' && b == '{') {
sta.pop();
}else{
return false;
}
}
}
return (sta.empty() == true ? true : false);
}
}