南阳ACM 括号匹配 JAVA

来源:互联网 发布:mac系统 盗版软件 编辑:程序博客网 时间:2024/04/27 18:25
import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Scanner;public class Main {    public static class BracketStack {        List<Character> s;        int top;        BracketStack() {            top = -1;            s = new LinkedList<Character>();        }        public void pop() {            s.remove(top--);        }                public void clear(){            s.clear();        }        public boolean push(char element) {            if (top < 0) {                s.add(element);                top++;                return true;            } else {                char topChar = s.get(top);                if (element == ']' || element == ')') {                    if (topChar + 1 == element || topChar + 2 == element) {                        pop();                        return true;                    } else {                        return false;                    }                } else {                    s.add(element);                    top++;                    return true;                }            }        }        public boolean isEmpty() {            return top == -1 ? true : false;        }    }    public static void main(String[] args) {        Scanner cin = new Scanner(System.in);        int size = Integer.parseInt(cin.nextLine());        List<Boolean> flags = new ArrayList<Boolean>();        BracketStack bs = null;        int j=0;        while (j++ <size) {            String input = cin.nextLine();            int length = input.length();            bs = new BracketStack();            for (int i = 0; i < length; i++) {                if (!bs.push(input.charAt(i))) {                    break;                }            }            if (bs.isEmpty()) {                flags.add(true);            }else{                flags.add(false);            }        }        for (int i = 0; i < flags.size(); i++) {            System.out.print(flags.get(i) ? "Yes" : "No");            if (i + 1 == flags.size())                continue;            System.out.print("\n");        }    }}

0 0
原创粉丝点击