有效括号
package com.jareny.jave.algorithm.stack;
import java.util.Stack;
/**
* 有效括号
*/
public class StackValid {
public static void main(String[] args) {
String str = "[]";
boolean valid = isValid(str);
System.out.println(valid);
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param s string字符串
* @return bool布尔型
*/
public static boolean isValid(String s) {
// write code here
if (s == null) {
return false;
}
Stack<Character> temp = new Stack<>();
for (char item : s.toCharArray()) {
if (item == '[') {
temp.push(']');
} else if (item == '{') {
temp.push('}');
} else if (item == '(') {
temp.push(')');
} else if (temp.isEmpty() || temp.pop() != item) {
//如果 还有数据 并且不是 [ { ( ,那么temp就是空的,不符合要求,或者弹出的元素不等于当前的 也不是
return false;
}
}
return temp.isEmpty();
}
}