Given a string containing just the characters '(', ')'
, '{'
, '}'
,'['
and ']'
, determine if the input string is valid.
用stack来处理,每次遇到左括号进栈,遇到右括号时,取栈顶并比较。
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
String s1 = "{([";
String s2 = "})]";
if(s.length() == 0) return true;
int index = 0;
while(index < s.length()) {
char c = s.charAt(index);
if(c == '(' || c == '{' || c == '[') stack.push(c);
else {
if(stack.isEmpty()) return false;
char tmp = stack.pop();
if(s2.indexOf(c) != s1.indexOf(tmp)) return false;
}
index++;
}
return stack.isEmpty() ? true : false;
}
}