1 package com.ceshi.zhongji; 2 3 /* 4 * 括號匹配打印0,不匹配打印1 5 * ([]([])) 6 */ 7 import java.util.ArrayList; 8 import java.util.List; 9 import java.util.Scanner; 10 11 public class KuoHao { 12 public static void main(String[] args) { 13 Scanner sc = new Scanner(System.in); 14 String input = sc.nextLine(); 15 KuoHao kh = new KuoHao(); 16 System.out.println(kh.testString(input)); 17 } 18 19 public int testString(String input) { 20 // 轉化成char數組 21 char[] oldChar = input.toCharArray(); 22 // new一個新數組 存放 "[" "(" ")" "]" 23 List<Character> list = new ArrayList<>(); 24 // 遍歷char數組 若是存在括號 則存入新的char[]中 25 for (int i = 0; i < oldChar.length; i++) { 26 if (oldChar[i] == '[' || oldChar[i] == ']' || oldChar[i] == '(' 27 || oldChar[i] == ')') { 28 list.add(oldChar[i]); 29 } 30 } 31 // 第一個是右括號或者前兩個都是直接返回1不匹配。其餘狀況遍歷對每個左括號其下一個必須爲右括號。 32 // 必須刪除全部匹配的,若是有剩餘說明有不匹配的。 33 while(list.size()!=0){ 34 if (list.get(list.size()-2) == '(' && list.get(list.size()-1) == ')') { 35 list.remove(list.size()-2); 36 list.remove(list.size()-1); 37 } 38 else if (list.get(list.size()-2) == '[' && list.get(list.size()-1) == ']') { 39 list.remove(list.size()-2); 40 list.remove(list.size()-1); 41 } 42 else{ 43 break;//不是上述狀況都不匹配。 44 } 45 46 } 47 if(list.size()>0){ 48 return 1; 49 } 50 else{ 51 return 0; 52 } 53 } 54 }