题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
JAVA
import java.util.*; //用栈 public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here //判断偶数 if(s.length() %2 != 0) return false; Stack<Character> stack = new Stack<Character>(); //左侧括号入栈 for(int i=0; i<s.length(); i++){ if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '['){ stack.push(s.charAt(i)); //依次和下面字符比较 如果遇到右侧括号就出栈 }else if(!stack.isEmpty() && s.charAt(i)== ')' && stack.peek() == '('){ stack.pop(); }else if(!stack.isEmpty() && s.charAt(i)== ']' && stack.peek() == '['){ stack.pop(); }else if(!stack.isEmpty() && s.charAt(i)== '}' && stack.peek() == '{'){ stack.pop(); } } //判断是否为空。 return stack.isEmpty(); } }