LeetCode--Valid Parentheses
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
注意:1、采用的是栈的方法,栈有五种基本的操作;而,由于stack是泛型,在new时要指定一个character类型;
2、java 的 &&:
(2)运算符优先级:
public class Solution {
public boolean isValid(String s) {
if(s.length()%2 !=0) return false;
Stack<Character> stack = new Stack<Character>();
for(int i=0, L=s.length(); i<L; i++) {
char ch = s.charAt(i);
if(ch==')' || ch==']' || ch=='}') {
if(stack.isEmpty()) return false;
if(ch==')' && stack.pop()!='(') return false; //这里要注意: &&前后两个表达式换过来是不成立的
if(ch==']' && stack.pop()!='[') return false;
if(ch=='}' && stack.pop()!='{') return false;
}
else stack.push(ch);
}
return stack.isEmpty() ? true : false;}
}

浙公网安备 33010602011771号