在此代码中添加一个检查Palindrome语句方法

时间:2017-08-21 07:37:45

标签: java palindrome

我如何实现一种检查输入是否是回文句子的方法? (忽略案例)

到目前为止,这是我的代码,它检查单数字是否是回文

import java.util.Stack;

public class PaliCh {

    private String inputString;
    private Stack<Character> characterStack = new Stack<Character>();

    public PaliCh() 
    {
        this.inputString = inputString;
        this.addStack();
    }

    private void addStack() 
    {
        for (int i = 0; i < this.inputString.length(); i++) 
        {
            this.characterStack.push(this.inputString.charAt(i));
        }

    }

    private String reverseStack() 
    {
        StringBuilder reverseInputString = new StringBuilder();
        while (!this.characterStack.isEmpty()) 
        {
            reverseInputString.append(this.characterStack.pop());
        }
        return reverseInputString.toString();
    }

    public boolean isPalindrome() 
    {
        return this.inputString.equals(this.reverseStack());
    }

} 

2 个答案:

答案 0 :(得分:0)

StringBuilder中,您已拥有.reverse()方法

StringBuilder stringBuilder = new StringBuilder("abba");

if(stringBuilder.toString().equals(stringBuilder.reverse().toString())) {
    System.out.println("Palindrom");
}

答案 1 :(得分:0)

或简单地说:

public static boolean isPalindrome(String s) {
   int i = 0;
   int j = s.length()-1;
   while (i < j) {
       if (s.charAt(i) != s.charAt(j)) {
           return false;
       }
       ++i;
       --j;
   }
   return true;
}

甚至:

public static boolean isPalindrome(String s) {
   for (int i = 0,j = s.length()-1; i < j; ++i, --j) {
       if (s.charAt(i) != s.charAt(j)) {
           return false;
       }
   }
   return true;
}