递归算法_Java程序使用递归检查回文字符串

递归算法_Java程序使用递归检查回文字符串_第1张图片

递归算法

检查字符串的快速指南是回文或不在Java中使用递归。

1.概述

在本教程中,我们将学习如何使用java中的递归函数来检查字符串是回文

字符串回文表示字符串反转值是否等于原始字符串

递归表示从同一函数调用一个函数。 这是一个计算机编程概念,用Java实现。

2. Java String Palindrome递归示例

下面的示例代码是使用递归方法实现的。 在那个方法中, isPalindrome()方法是从具有原始字符串的子字符串值的同一方法中调用的。

例:

步骤1:输入字串为:女士

步骤2:首次调用isPalindrome (“女士”)–第一个和最后一个字符相同-> m == m-> true

步骤3:接下来,用“ ada”调用相同的isPalindrome(“ ada”) –第一个和最后一个字符相同-> a == a- > true

步骤4:接下来,再次调用具有“ d”值的相同方法isPalindrome()。 现在,第一个if条件检查该字符串的长度为1,因此它返回true。 该值传递到上一步,其中输入为“ ada”。

步骤5:再次从“ ada”调用返回真实值到“ madam”输入调用。 因此,最后它返回true到main方法。

所有这些方法都放置在运行时堆栈中,并将从顶部调用。

如果输入为1234,则第一个字符和最后一个字符不同,因此最终返回false。 因此,字符串1234不是回文。

package com.javaprogramto.programs.strings;

public class StringPalindromeRecursiveExample {

	public static void main(String[] args) {
		// input string 1234
		String string = "1234";
		/*
		 * If function returns true then the string is palindrome otherwise not
		 */
		if (isPalindrome(string))
			System.out.println(string + " is a palindrome");
		else
			System.out.println(string + " is not a palindrome");

		// input string 1234
		String string2 = "madam";
		/*
		 * If function returns true then the string is palindrome otherwise not
		 */
		if (isPalindrome(string2))
			System.out.println(string2 + " is a palindrome");
		else
			System.out.println(string2 + " is not a palindrome");

	}

	/**
	 * Recursive function to check the string is palindrome or not.
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isPalindrome(String s) {

		// if the string has one or zero characters then recursive call is stopped.
		if (s.length() == 0 || s.length() == 1)
			return true;

		// checking the first and last character of the string. if equals then call the
		// same function with substring from index 1 to length -1. Because substring
		// excludes the endIndex.
		// if these two values are not same then string is not Palindrome so this
		// returns false.
		if (s.charAt(0) == s.charAt(s.length() - 1))
			return isPalindrome(s.substring(1, s.length() - 1));

		// this statment is executed if and if only first and last character of string
		// at any time is not equal.
		return false;
	}
}

输出:

1234 is not a palindrome
madam is a palindrome

3.结论

在本文中,我们已经看到了如何在java中使用递归方法检查字符串是否为回文

的GitHub

翻译自: https://www.javacodegeeks.com/2020/12/java-program-to-check-palindrome-string-using-recursion.html

递归算法

你可能感兴趣的:(字符串,算法,java,python,leetcode)