一、问题:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
二、解题思路
这个问题是括号匹配,显然要用到栈类解题。
- 每次字符都要与栈顶元素比较,如果可以匹配,则移除栈顶元素
- 不能匹配,则将字符压入栈中
- 最后全部字符都遍历(与栈顶元素比较)一遍之后,看栈中是否还有元素,若有,则返回false,反之,返回true
三、我的代码
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i <= s.length() - 1; i++){
String goal = s.substring(i,i+1);
int num=0;
if("{".equals(goal))
num = -1;
if("}".equals(goal))
num = 1;
if("(".equals(goal))
num = -2;
if(")".equals(goal))
num = 2;
if("[".equals(goal))
num = -3;
if("]".equals(goal))
num = 3;
if(num == 0)
return false;
if(stack.isEmpty())
stack.push(num);
else{
if(num+stack.peek()==0)
stack.pop();
else
stack.push(num);
}
}
if(stack.isEmpty())
return true;
return false;
}
}