编写一个Java程序以使用递归检查回文字符串 [英] Write a java program to check palindrome string using recursion

查看:186
本文介绍了编写一个Java程序以使用递归检查回文字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package beginnersbook.com;
导入java.util.Scanner;
PalindromeCheck类
{
//我的检查方法
公共静态布尔isPal(String s)
{//如果长度为0或1,则字符串为回文
if(s.length()== 0 || s.length()== 1)
返回true;
if(s.charAt(0)== s.charAt(s.length()-1))
/*检查字符串的第一个和最后一个字符:
*如果它们相同,则对子字符串执行相同的操作
*删除第一个和最后一个字符.并进行这个
*直到字符串完成或条件失败
*函数调用本身:递归
*/
返回isPal(s.substring(1,s.length()-1));

/*如果程序控制到达此语句,则表示
*字符串不是回文,因此返回false.
*/

我尝试过的事情:

我想针对这个具有时间和空间复杂性的问题的最佳程序.

package beginnersbook.com;
import java.util.Scanner;
class PalindromeCheck
{
//My Method to check
public static boolean isPal(String s)
{ // if length is 0 or 1 then String is palindrome
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails
* Function calling itself: Recursion
*/
return isPal(s.substring(1, s.length()-1));

/* If program control reaches to this statement it means
* the String is not palindrome hence return false.
*/

What I have tried:

i want best program for this question with time and space complexity

推荐答案

我们不做您的作业:它的设置是有原因的.在这里,您可以考虑自己被告知的内容,并尝试理解它.也可以在那里帮助您的导师识别您的弱点,并将更多的注意力放在补救措施上.

自己尝试,您可能会发现它并不像您想的那么难!

如果您遇到特定问题,请询问此问题,我们将尽最大努力为您提供帮助.但是我们不会为您做所有这一切!
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren''t going to do it all for you!


我会尝试替换
I would try to replace
return isPal(s.substring(1, s.length()-1));




with

return isPal(s.substring(1, s.length()-2));


语录:

我希望这个问题具有时间和空间复杂性的最佳解决方案

i want best program for this question with time and space complexity


如果不是出于学习目的,则递归是一个不好的解决方案,循环会更有效.


If not for learning purpose, recursion is a bad solution, a loop will be more efficient.


这篇关于编写一个Java程序以使用递归检查回文字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆