给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’,’<’,’>’, 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
譬如:"()[]{}“为合法,”(]"、"([)]"均为非法。
**解题思路:**栈的思想,遇到左括号入栈,右括号出栈并检查是否匹配,如果不匹配则非法。如果整个字符串遍历完了且栈也为空,则合法。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String instring = sc.nextLine();
String str[] = instring.split("");
int len = str.length;
Stack<String> str1 = new Stack<String>();
int pd = 1;
if(len%2 ==1 || len == 0){
pd = 0;
}
if(isright(str[0])){ // 判断第一个是否为左括号
pd = 0;
for(int i=1;i<len;i++){
if(isleft(str[i])){
str1.push(str[1]); // 左括进栈
}else{
if(str[i].equals(bh(str1.peek()))){ // 右括匹配出栈
str1.pop();
}else{
pd = 0;
}
}
}
}
// 检查栈是否为空
if(!str1.empty()){
pd = 0;
}
System.out.println(pd);
}
// 左右括对应关系
public static String bh(String str1){
String str2 = null;
if(str1.equals("(")){
str2 = ")";
}
if(str1.equals("[")){
str2 = "]";
}
if(str1.equals("{")){
str2 = "}";
}
if(str1.equals("<")){
str2 = ">";
}
return str2;
}
//判断是否为左右括号
public static boolean isleft(String str){
if(str.equals("(") || str.equals("[") || str.equals("{") || str.equals("<")){
return true;
}else{
return false;
}
}
public static boolean isright(String str){
if(str.equals(")") || str.equals("]") || str.equals("}") || str.equals(">")){
return true;
}else{
return false;
}
}
}