如何使java中使用递归的回文程序忽略字符串中所有位置的特殊字符?



我的回文程序有一个轻微的逻辑错误,当我在字符串的前面或末尾插入特殊字符时,我得到一个字符串不是回文的指示。我正在编程回文,以便在考虑字符串时忽略所有特殊字符。例如,@bob将被认为不是回文,而b@ob将被认为是回文。我将如何编辑我的代码,使特殊字符被忽略,而不管位置在哪里?所有这些都是通过递归完成的。

"

进口java.util.Scanner;

公共类recursionExercise {

//the recursive function that checks to see whether the 
//string is a palindrone or not
public static boolean checkPalindrome(String str, int firstChar, int lastChar) {
//if only one character exists
if (firstChar == lastChar) 
return true;

//checks to see if the first and last characters match
if ((str.charAt(firstChar)) != (str.charAt(lastChar))) 

return false;

//checks to see if it has characters
if (!isChar(str))
return true;


//checks the middle strings with multiple characters
//on whether or not they are a palindrome with recursive method
if (firstChar < lastChar + 1)
return checkPalindrome(str, firstChar + 1, lastChar - 1 );
return true;

}
//method that actually determines what a palindrome is
public static boolean isAPalindrome(String str) {

int n = str.length();
//if string is not 0 or 1 then it's a palindrome
if(n == 0 || n == 1) 
return false;
return checkPalindrome(str, 0, n - 1);

}
//method that checks for characters
public static boolean isChar(String str) {

for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!Character.isLetter(c) && !Character.isDigit(c))
return false;
}
return true;
}
//tests out recursive methods
public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string to see if it's a palindrome:");

String str = scanner.nextLine(); //input from the user


//checks to see if it's a palindrome and puts them all
//to be lower case to ignore the case issue
if(isAPalindrome(str.toLowerCase()))
System.out.println(str+" is a palindrome");

else
System.out.println(str+" is not a palindrome");

scanner.close();
}

}

"

这个对我来说太棒了!我现在正在学习这个问题,我正在网上寻找一些帮助。没有运气!!我在检查一个单词是否为回文时没有任何问题,但当涉及到句子时,我就很纠结了。所以我必须找出一种方法来摆脱字符串中的空格,但同时保持原始字符串的完整性。我尝试了很多方法,但这是唯一一种对我有效的方法,并且通过了电子书的所有测试。希望这对你有帮助!

import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String userText;
String backText = "";
String userTextNoSpace = "";
int i;
userText = scnr.nextLine();
if (userText.contains(" ")) {
userTextNoSpace = userText.replace(" ", "");
for (i = userTextNoSpace.length() - 1; i >= 0; --i) {
backText += userTextNoSpace.charAt(i);
}
} else {
for (i = userText.length() - 1; i >= 0; --i) {
backText += userText.charAt(i);
}
}
if (backText.equalsIgnoreCase(userTextNoSpace) || backText.equalsIgnoreCase(userText)) {
System.out.println( userText + " is a palindrome");
} else {
System.out.println(userText + " is not a palindrome");
}
}
}

相关内容

  • 没有找到相关文章

最新更新