给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
import java.util.Scanner;
import java.util.Stack;
public class Solution{
public boolean isValid(){
Scanner input =new Scanner(System.in);
String s =input.nextLine();
Stack stack =new Stack<>();
char[] chars =s.toCharArray();
if(chars[0] == ')' || chars[0] == ']' || chars[0] == '}'){
return false;
}
for (char aChar :chars) {
if(aChar ==' '){
continue;
}
if (stack.empty()) {
stack.push(aChar);
}else if (isTrue(stack.peek(),aChar)) {
stack.pop();
}else {
stack.push(aChar);
}
}
return stack.empty();
}
private boolean isTrue(char c1,char c2) {
return (c1 =='(' &&c2 ==')') || (c1 =='[' &&c2 ==']') || (c1 =='{' &&c2 =='}');
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.isValid());
}
}