一、问题描述
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.
二、问题分析
使用Stack进栈、出栈操作即可实现。
三、算法代码
public class Solution {
public boolean isValid(String s) {
String left = "([{";
String right = ")]}";
Stack<Character> stack = new Stack<Character>();
char c;
for(int i = 0; i < s.length(); i++){
c = s.charAt(i);
if(left.indexOf(c) != -1){
stack.push(c);
}else{
if(stack.isEmpty() || stack.peek() != left.charAt(right.indexOf(c))){
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
}