题解 | #有效括号序列#
有效括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValid (String s) {
// write code here
Stack<Character> stack=new Stack<>();
for(char c:s.toCharArray()){
if(c=='(')
stack.push(')');
else if(c=='{')
stack.push('}');
else if(c=='[')
stack.push(']');
//这里的stack.isEmpty()对付只有后半段的符号
else if(stack.isEmpty()||stack.pop()!=c) return false;
}
//这里的stack.isEmpty()对付只有前半段的符号
return stack.isEmpty();
}
}