zoukankan      html  css  js  c++  java
  • 括号匹配

     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 }
  • 相关阅读:
    2015.07-2015.08
    the last lecture
    强化的单例属性_Effective Java
    Socket通信客户端设计(Java)
    静态工场方法代替构造器
    如何控制Java中的线程,总结了3种方法...
    如何快速转型,比如C#...to...Java
    C#中var和dynamic
    How to use the Visual Studio
    mark blog
  • 原文地址:https://www.cnblogs.com/wushuai-study/p/4737396.html
Copyright © 2011-2022 走看看