我的任务是写一个类的方法,我测试用户输入的回文。该类必须具有递归方法,并且该方法必须调用一个帮助器方法,该方法可以删除空格,标点符号并忽略大小写。哪一种更合理的递归辅助方法?
我有两个工作类来做这些事情,但我想知道哪个结构更好地工作,哪个帮助器方法实际上符合辅助方法的描述。
这里的第一类:
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;
}
}
第二个impl。适合“帮助者的方法,删除空格,标点符号,并忽略案件”显然 – 2012-12-22 05:52:48
有什么办法让第二个更有效?每当Palindrome重复出现时,它会在第一次调用帮助程序后调用不需要的帮助程序方法。 –
然后,只需将PalindromHelper()调用下的所有内容都拉入新方法(例如PalindromRecurse()),然后递归调用它。 –