• 括号匹配


     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 }
  • 相关阅读:
    05--STL序列容器(List和Forward_list)
    04--STL序列容器(Stack和Queue)
    03--STL序列容器(Deque)
    STL迭代器iterator
    02--STL序列容器(Vector)
    C++回顾day03---<string字符串操作>
    C++回顾day03---<输入输出流>
    C++回顾day03---<异常>
    16位结构的CPU,8086给出物理地址的方法
    初识STM32固件库
  • 原文地址:https://www.cnblogs.com/wushuai-study/p/4737396.html
Copyright © 2020-2023  润新知