啊哈之队列,栈练习

package com.company.algorithm.A20211126;

public class Structure {
    // 先进先出 队列
    private static class Q {
        int head;
        int tail;
        int[] data = new int[101];
    }

    // 将队列第一个数删除第二个数放在最后,依次循环到队列没有数据为止,删除掉的数字顺序是新的结果
    private static void QueueTest() {
        Q q = new Q();
        int[] d = {0,6,3,1,7,5,8,9,2,4};
        int[] res = new int[d.length];
        int cur = 1;
        for (int i = 1; i < d.length; i++) {
            q.data[i] = d[i];
        }
        q.head = 1;
        q.tail = 10;

        while (q.head < q.tail) {
            res[cur++] = q.data[q.head];
            q.head++;
            q.data[q.tail++] = q.data[q.head];
            q.head++;
        }

        for (int i = 1; i < res.length; i++) {
            System.out.print(res[i]);
        }
    }

    // 先进后出 栈
    private static void huiWen() {
//        String str = "{}{[([])]()}";
 //       String str = "{{[()()}]}";
        String str = "{{}[{( )}]}()";

        int top = -1, idx = 0;
        StringBuilder sb = new StringBuilder();
        while (idx < str.length()) {
            while (sb.length() > 0) {
                if(sb.charAt(top) == '{' && str.charAt(idx) == '}') {
                    sb.deleteCharAt(top);
                    top--;
                    idx++;
                }
                else if(sb.charAt(top) == '[' && str.charAt(idx) == ']') {
                    sb.deleteCharAt(top);
                    top--;
                    idx++;
                }
                else if(sb.charAt(top) == '(' && str.charAt(idx) == ')') {
                    sb.deleteCharAt(top);
                    top--;
                    idx++;
                } else break;
            }

            if(idx < str.length()) {
                sb.append(str.charAt(idx));
                top++;
                idx++;
            }
        }

        System.out.println(top == -1);
    }

    public static void main(String[] args) {
        //QueueTest();
        huiWen();
    }
}

 

上一篇:NLP - pytorch 实现 word2vec(简单版)


下一篇:贪心问题-区间分组