package com.sjtu.design.excise; import java.util.List; import java.util.ArrayList; import java.util.Scanner; /** * @class 回文類 * @author TangShuGuang */ public class Palindrome { private Object stackElem[]; private int top; private static Scanner input; // 初始化棧 public Palindrome() { stackElem = new Object[100]; top = 0; } public int length() { return this.top; } // 入棧 public void push(Object stack) { if (top == stackElem.length) { // throw new Exception("棧已滿!"); System.out.println("棧已滿!"); } else { stackElem[top++] = stack; System.out.println("入棧" + stack); } } // 出棧 public Object pop() { if (top == 0) { // throw new Exception("棧為空!"); System.out.println("棧為空!"); return null; } else { return stackElem[--top];// 刪除然后返回現(xiàn)在的棧頂 } } /** * 判斷輸入字符串是否為回文 * * @param word * 輸入待判定的字符串 *//* * public void isPalindrome2(String word) { int len = word.length(); int mid = * len / 2; String rword = ""; * * for (int i = 0; i < mid; i++) { this.push(i); } while (this.length() > 0) { * rword += this.pop(); } if (word == rword) { System.out.println("Right!"); } * else { System.out.println("Wrong!"); } } */ /** * 判斷輸入字符串是否為回文 * * @param pValue * 輸入待判定的字符串 */ public void isPalindrome(String pValue) { // 堆棧一 List<Character> stack = new ArrayList<Character>(); // 堆棧二 List<Character> stack2 = new ArrayList<Character>(); // 字符串長(zhǎng)度的一半 int haflen = pValue.length() / 2; for (int i = 0; i < haflen; i++) { // 字符進(jìn)棧 stack.add(pValue.charAt(i)); // 倒序進(jìn)棧 stack2.add(pValue.charAt(pValue.length() - i - 1)); } // 標(biāo)識(shí)符 boolean bFlag = true; // 出棧并比較 for (int i = haflen - 1; i >= 0; i--) { if (stack.remove(i) != stack2.remove(i)) { bFlag = false; break; } } // 返回比對(duì)結(jié)果 if (bFlag) { System.out.println("Right!"); } else { System.out.println("Wrong!"); } } public static void main(String[] args) { Palindrome p = new Palindrome(); //input = new Scanner(System.in); //String word = input.next(); String testData[] = { "123456", "abba", "cba", "12AB21" }; for (int i = 0; i < testData.length; i++) { System.out.println("請(qǐng)輸入字符:" + testData[i]); p.isPalindrome(testData[i]); } } } |
|