题解 | #合法括号序列判断#
合法括号序列判断
http://www.nowcoder.com/practice/d8acfa0619814b2d98f12c071aef20d4
会不会有点啰嗦。。。
import java.util.*;
public class Parenthesis {
public boolean chkParenthesis(String A, int n) {
if (A.length() != n) return false;
if (A.length() == 0) return true;
char[] chars = A.toCharArray();
Stack<Character> stack = new Stack<>();
for (char aChar : chars) {
if (aChar == '('){
stack.push(aChar);
} else if (aChar == ')'){
if (!stack.empty() && stack.peek() == '('){
stack.pop();
} else {
stack.push(aChar);
}
} else{
return false;
}
}
return stack.empty();
}
}