我的任务是为一个测试用户输入的回文的类编写方法。该类必须有一个递归方法,并且该方法必须调用一个辅助方法来删除空格、标点符号并忽略大小写。
我有两个工作类来做这些事情,但我想知道哪个结构效果更好,哪个辅助方法实际上适合辅助方法的描述。
这是第一堂课:
public class RecursivePalindrome
{
public boolean Palindrome(String s)
{
return PalindromeHelper(s);
}
public boolean PalindromeHelper(String s)
{
String a = s.toLowerCase(); //Converts any capital letters to lowercase beforte analyzing the string
a = a.replaceAll(" ", ""); //Removes any and all spaces in the string
for(int i = 0; i < a.length(); i++) //Removes punctuation by using isLetter method from Character Class
{
if(Character.isLetter(a.charAt(i)) == false)
a = a.replace(a.substring(i, i+1), "");
}
if(a.length() == 0 || a.length() == 1)
return true;
else if(a.charAt(0) == (a.charAt(a.length() - 1)))
return PalindromeHelper(a.substring(1, a.length() - 1));
else
return false;
}
}
第二个:
public class Recurs
{
public boolean Palindrome(String s)
{
String l = PalindromeHelper(s);
if(l.length() == 0 || l.length() == 1)
return true;
else if(l.charAt(0) == (l.charAt(l.length() - 1)))
return Palindrome(l.substring(1, l.length() - 1));
else
return false;
}
public String PalindromeHelper(String s)
{
s = s.toLowerCase(); //Converts any capital letters to lowercase before analyzing the string
s = s.replaceAll(" ", ""); //Removes any and all spaces in the string
for(int i = 0; i < s.length(); i++) //Removes punctuation by using isLetter method from Character Class
{
if(Character.isLetter(s.charAt(i)) == false)
s = s.replace(s.substring(i, i+1), "");
}
return s;
}
}