Java中栈的应用,括号匹配

 1 package edu.yuliang.Data_Structure_Basics;
 2 
 3 import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
 4 /*
 5 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
 6 
 7 有效字符串需满足:
 8 
 9 左括号必须用相同类型的右括号闭合。
10 左括号必须以正确的顺序闭合。
11 注意空字符串可被认为是有效字符串。
12 
13 
14 实现思路:
15 
16 {  [  (  )  ]  }
17 
18 1、依次遍历字符串,只要是{  [  (  都把它压入栈中
19 
20 2、如果是  )   ]    }    则先后判断栈顶元素是否为(  ,如果是则匹配成功,栈顶中  (  出栈,不是则返回false,不匹配
21 
22 3、判断栈顶元素是否为 ] ,如果是则匹配成功,栈顶中  [  出栈
23 
24 4、判断栈顶元素是否为 } ,如果是则匹配成功,栈顶中  {  出栈
25 
26 5、判断栈中是否还存在元素,如果不存在则表示之前已经全部匹配出栈,如果还存在则表示部分未匹配,判断依据,stack.isEmpty()。
27 
28  */
29 
30 import java.util.Scanner;
31 import java.util.Stack;
32 
33 public class stack_match {
34     public static void main(String[] args) {
35         Stack stack =new Stack();
36         Scanner scanner  =new Scanner(System.in);
37 
38 
39         //char[] arr =string.toCharArray();
40         //System.out.println(string.length());
41         //System.out.println(arr.length);一样长
42         while (scanner.hasNext()){
43             String string = scanner.next();
44             boolean is_match=match(string);
45             System.out.println(is_match);
46 
47         }
48 
49 
50 
51 
52     }
53     public static Boolean match(String string){
54         //申明一个stack
55 
56         Stack stack =new Stack();
57         //遍历 string
58         for (int i = 0; i <string.length() ; i++) {
59             char c =string.charAt(i);
60             if(c=='{'||c=='['||c=='('){
61                 //左括号压入栈中
62                 stack.push(c);
63 
64             }
65             else {
66                 //若不是就行对比
67                 if(stack.isEmpty()){
68                     return false;
69                 }
70                 char top_char= (char) stack.pop();
71                 if((c==')'&&top_char=='(')||(c==']'&&top_char=='[')||(c=='}'&&top_char=='{')){
72                     //若是匹配了就不用在次push里面
73                 }
74                 else {
75                     stack.push(top_char);
76                 }
77             }
78         }
79         //最后为空的话就输出匹配
80         if(stack.isEmpty())
81             return true;
82 
83         return false;
84     }
85 }

猜你喜欢

转载自www.cnblogs.com/AnonymousDestroyer/p/10624766.html