给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
public class title20 {
public static void main(String[] args) {
String s = "(]";
if (isValid(s)){
System.out.println(true);
}else {
System.out.println(false);
}
}
public static boolean isValid(String s) {
Stack stack = new Stack();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch); //1.判断字符串中的括号,左括号则入栈
} else if (stack.isEmpty()) { //2.右括号,先判断栈是否为空
return false;
} else {
char top = (char) stack.pop(); //3.不为空,弹出栈顶元素,与右括号比较
if (top == '(' && ch == ')') {
continue;
} else if (top == '[' && ch == ']') {
continue;
} else if (top == '{' && ch == '}') {
continue;
} else {
return false;
}
}
}
if(!stack.isEmpty()){
return false;
}
return true;
}
}