基础-栈数据结构

栈:只能先进后出,被限定为只能在一端进行插入和删除操作,可以用来验证字符串是否是回文序列

package com.nxz.blog.otherTest;

import java.util.Stack;

public class Test01 {

    public static void main(String[] args) {
        testStack("ahha啊k1k啊ahha");
        testStack("ahha啊kk啊ahha");
        testStack("ahha啊kk1啊ahha");
    }

    /**
     * 判断是否是回文序列
     * 关键点是获取mid节点,判断mid之前和之后是否是对应的
     *
     * @param str
     */
    public static void testStack(String str) {

        int mid = str.length() / 2;
        Stack stack = new Stack();
        //将中间节点之前的数据入栈
        for (int i = 0; i < mid; i++) {
            stack.push(str.charAt(i));
        }

        //后序节点的起始索引需要进行处理,整个字符串为奇数个则next为mid,否则为mid+1
        int next = 0;
        if (str.length() % 2 == 0) {
            next = mid;
        } else {
            next = mid + 1;
        }
        //将中间节点之后的数据和出栈之后的数据比较,同则继续,不同则表示不是回文
        for (int i = next; i < str.length(); i++) {
            if (str.charAt(i) != (char) stack.pop()) {
                System.out.println("不是");
                return;
            }
        }
        System.out.println("是");

    }
}

输出结果:

是
是
不是
原文地址:https://www.cnblogs.com/nxzblogs/p/11143633.html