1. 程式人生 > >算法——回文解密,判斷一個素組是否為回文

算法——回文解密,判斷一個素組是否為回文

隊列 div ack span 獲取 解密 get 隨機 void

算法中,隊列是先進先出原則,而棧是後進先出原則,棧限定只能在一端進行插入和刪除操作,而棧的作用有哪些?

可以通過一組回文字符串來看:“xyzyx”,同過棧來判斷字符串是否是回文

案例:package test;

/**
 * @author dayu 解密回文——棧
 * @version 創建時間:2017年11月13日 下午2:15:01
 *          類說明
 */
public class zhan
{
    //回文——一定有對稱軸,所以一定是單數
    public static void main(String[] args)
    {
        String str 
= "azhohza";//隨機給定一組就可以 int len=str.length(); int mid = len / 2 ;//獲取中點位置 System.out.println("mid="+mid); //取兩個數組chara,charb,長度為給定字符串的長度 byte[] bytes = str.getBytes(); char[] charb = new char[len]; char[] chara = new char[len];
//charb數組全部賦值 for (int i = 0; i < len; i++) { charb[i] = (char)bytes[i]; } //初始化棧,top=0,然後將中點之前的所有值依次入棧 int top = 0; for (int i = 0; i < mid; i++) { chara[++top] = (char)charb[i]; System.out.print("-"+charb[i]); } System.out.println(
"\ntop==="+top);
//根據中心對稱來判斷,如果top=0,說明棧裏面的所有字符一一匹配了
for (int i = mid + 1; i < len ; i++) { if (charb[i] != chara[top]) { break; } top--; } if (top == 0) System.out.println("是回文"); else System.out.println("不是回文"); } }

算法——回文解密,判斷一個素組是否為回文