java - 如何让回文程序不识别空格并以句点结尾?

标签 java arrays whitespace palindrome period

我需要帮助我已经尝试查找许多方法,但似乎无法使其发挥作用。我需要这个不识别空格,所以如果用户输入 level ,它应该说,“是的,它是一个回文”,就像它是 level//没有空格一样。用户输入需要以句点结束,并且程序不应考虑该句点。这么有水平。应该返回 true。

import java.util.Scanner;

public class PalindromeDemo
{
public static void main(String[] args)
{
    String phrase, answer;
    Scanner keyboard = new Scanner(System.in);
    do
    {
        System.out.println("I will determine if a string is a palindrome");
        System.out.println("Enter a word or characters and end it with a period");
        phrase = keyboard.nextLine();

        Palindrome pd = new Palindrome();
        if(pd.checkPalindrome(phrase))

                System.out.println("YES, the phrase is palindrome!");
            else
                System.out.println("NO, the phrase is NOT palindrome.");
                System.out.println();
                System.out.println("Would you like to continue? Enter yes or no");
                answer = keyboard.nextLine();
                System.out.println();
    }
    while(answer.equalsIgnoreCase("yes"));
}
}


public class Palindrome
{
public static final int MAX_CHARS = 80;

public boolean checkPalindrome(String text)
{
    char[] array = new char[80];
    int length = text.length();

    String reverseText = "";

    for(int i = length-1; i >= 0; i--)
    {
         reverseText = reverseText + text.charAt(i);
    }

    if(reverseText.equalsIgnoreCase(text))
    {
        return true;
    }

    else
    {
        return false;
    }
}
}

最佳答案

试试这个。输入字符串不会改变,这比上面建议的更快、更高效。

public static boolean checkPalindrome(String input){
    //input always contains period in the end.
    //ignore it.
    int length = input.length()-1-1;
    int i= 0;
    int j= length;
    while(i<j){
        if(input.charAt(i) == ' '){
            i++;
        } if (input.charAt(j) == ' '){
            j--;
        }
        if(input.charAt(i) ==input.charAt(j)){
            i++;
            j--;
        }else{
            return false;
        }
    }
    return true;

}

关于java - 如何让回文程序不识别空格并以句点结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35621080/

相关文章:

java - Deeplearning4j 将模型解析为数据集

Java 套接字错误 : Reading Strings from Socket's InputStream

java - Java 构造函数中的错误(找不到符号)

Java Regex - 检查回车符

java - JFugue - 幻灯片/弯音

arrays - VBA 中的最长公共(public)子序列给出#VALUE!错误

javascript - 向数组添加多个输入字段的问题

java - 在java中打印N维数组

git - 为什么 git 关心我文件中的尾随空格?

Ruby:删除字符串开头的空白字符