gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:21:01 25 4
gpt4 key购买 nike

我需要帮助我已经尝试查找许多方法,但似乎无法使其发挥作用。我需要这个不识别空格,所以如果用户输入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com