题目如下:
实现的过程中需要使用到stack(栈),栈有别于arraylist等,新添加一个数便将该数存在栈的顶端。
java中栈的函数:
Stack stack=new Stack();可以实现泛型形式
stack.push();向栈中添加数据
stack.peek();栈的顶部的数据
stack.isEmpty();
下面是算法实现的代码;
public static boolean isValid(String s) {
if (s.isEmpty())
return true;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}