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];// 删除然后返回现在的栈顶 } } /** * 判断输入字符串是否为回文 * * @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>(); // 字符串长度的一半 int haflen = pValue.length() / 2; for (int i = 0; i < haflen; i++) { // 字符进栈 stack.add(pValue.charAt(i)); // 倒序进栈 stack2.add(pValue.charAt(pValue.length() - i - 1)); } // 标识符 boolean bFlag = true; // 出栈并比较 for (int i = haflen - 1; i >= 0; i--) { if (stack.remove(i) != stack2.remove(i)) { bFlag = false; break; } } // 返回比对结果 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("请输入字符:" + testData[i]); p.isPalindrome(testData[i]); } } } |
|
来自: _bolo > 《DataStructure》