Valid Palindrome [duplicate] - java

This question already has answers here:
Check string for palindrome
(42 answers)
Closed 2 years ago.
Problem is to check if the string is valid palindrome or not. Return true for empty strings.
What's the problem with my code? It is failing for the input "ab"
public class Solution {
Boolean b;
public Boolean isPalindrome(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-zA-Z0-9]","");
if(s.length()==1 || s.isEmpty())
{
return true;
}
for (int i=0;i<s.length()-1;i++)
{
b = expandAroundCenter(s,i,i+1);
b = expandAroundCenter(s,i,i);
}
return b;
}
public Boolean expandAroundCenter(String s,int start,int end)
{
while(start>=0 && end<s.length() )
{
if ((s.charAt(start))!=(s.charAt(end)))
{
return false;
}
start--;
end++;
}
return true;
}
}

You've got big logic flaws here.
Firstly, in your for loop you call expandAroundCenter twice, and overwrite the first results.
Secondly, you're doing this in a for loop, and overwriting all previous results.
Also I think you're making things harder than they need to be by starting in the middle. Start on the edges, and work inward!
Calculating a palindrome is a great opportunity for a recursive function (one that calls itself). I'll give you the pseudo-code, it's up to you to implement:
public Boolean IsPalindrome(string s)
// If we are down to 1 or zero characters, success!
// This deals nicely with odd numbered length strings
if(length <= 1)
return true;
// If the first and last don't match, it's not a palindrome
if(first letter != last letter)
return false;
// Since we know the first and last match, strip them off, then repeat
return IsPalindrome(strip first and last letter from string)
}

If there are no constraints, the best way to solve this problem is to use recursive.
class palindrome
{
static boolean isPalRec(String str,
int s, int e)
{
if(s == "")
return true;
if (s == e)
return true;
if ((str.charAt(s)) != (str.charAt(e)))
return false;
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);
return true;
}
static boolean isPalindrome(String str)
{
int n = str.length();
if (n == 0)
return true;
return isPalRec(str, 0, n - 1);
}
}

Related

How to check if a string is only number values

I am trying to run a recursion function where i check each character in the string to see if the character is a numeric number, however im a little stuck as the function runs and only checks the first character of the string
public static boolean isNumeric(String str) {
if(str == null)
{
return false;
}
if(str=="") {
return true;
}
char first = str.charAt(0);
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
String reduced = str.substring(1);
return isNumeric((reduced)); }
Not 100% sure if I understood you correctly. If you want to check, if the string contains numeric values just see my other examples further down.
Otherwise, if you want to check, if the string contains exclusively numerical signs and digits you could do something like:
public static boolean isInteger(String numericValue) {
if (numericValue == null) return false;
try {
Integer.parseInt(numericValue);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Please note, that this example does only work for Integers. If you
want to use bigger numbers, we can use Long or even BigDecimal
instead. But the main idea stays the same - check, if it can be parsed.
Or probably more appealing:
public static void main(String args[]) {
System.out.println(MyClass.isNumeric(""));
System.out.println(MyClass.isNumeric(null));
System.out.println(MyClass.isNumeric("abc"));
System.out.println(MyClass.isNumeric("a2b"));
System.out.println(MyClass.isNumeric("1a2b3"));
System.out.println(MyClass.isNumeric("42"));
System.out.println(MyClass.isNumeric("-100"));
}
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
// to make sure that the input is numeric, we have to go through the characters
for (char c : str.toCharArray()) {
if (!Character.isDigit(c)) return false; // we found a non-digit character so we can early return
}
return true;
}
This will only print true for 42. The other examples contain other characters, too.
There are multiple issues with your code:
if(str=="") {
return true;
}
For string comparison you should use the String.equals() method - there are alternatives to that for example for your use-case you could use the convenience method String.isEmpty() or you could also just check the length of the string.
if(Character.isDigit(first))
{
return true;
}
if(Character.isDigit(first) == false)
{
return false;
}
This is some kind of if-else structure here. No need to check the same condition twice. Besides, it won't work with your recursive approach, because for what you want to achieve you need the current state which is "have I already found a digit". You could solve that with a memoized recursive function where you pass the current state along as a second argument to each subsequent call.
In your case it will return the result of the latest iteration / the
latest character.
You could do something like the following instead of using recursion. Recursion is fine, but it also comes with some costs. For example is it arguably harder to read and maintain.
public static void main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false; // handle null-pointer
if (str.length() == 0) return false; // handle empty strings
boolean atLeastOneDigit = false;
// to make sure that the input is numeric, we have to go through the characters
// until we find the first one then we can early return
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
atLeastOneDigit = true; // we found a digit, therefore it must be numeric
break; // early return to save some iterations
}
}
return atLeastOneDigit;
}
The output of the program is:
false
false
false
true
true
true
true
Another alternative is to use Regex:
private static final Pattern digitRegex = Pattern.compile("\\d+");
public static main() { ... } // same as above
public static boolean isNumeric(String str) {
if (str == null) return false;
Matcher matcher = MyClass.digitRegex.matcher(str);
return matcher.find();
}
I am trying to explain you to solve this problem by two string methods that is isDigit(character) and charAt(i). In this case we will try to solve this problem by for loop. we will apply for loop in order to check every character of a string whether it is digit or not. If it is digit we will return true otherwise false.
Code is looks like this :
import java.lang.*;
import java.util.Scanner;
class Main {
public boolean containsDigit(String str) {
byte flag = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
flag = 1;
}
}
if (flag == 1) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string : ");
String str = sc.nextLine();
Main test = new Main();
boolean chkDigit = test.containsDigit(str);
if (chkDigit == true) {
System.out.println("String contains digit.");
} else {
System.out.println("String doesn't contain any digit.");
}
}
}

To check if string is palindrome using recursion?

There is something wrong with my code as one the testcase in my assignment is coming out wrong, giving me runtime error when I submit the code online. That testcase could be any String. I believe that everything is fine with the code as I have checked it manually for many testcases.
HERE IS THE CODE
public static boolean isStringPalindrome(String input) {
if(input.length()==0 || input.length()==1)
return true;
int first = 0;
int last = input.length()-1;
if(input.charAt(first) != input.charAt(last))
return false;
String str="";
for(int i=first+1;i<last;i++){
str = str+input.charAt(i);
}
boolean sa = isStringPalindrome(str);
return sa;
}
Sample Input
racecar
Output
true
Sample Input
pablo
Output
false
Your code appears to be overly complicated for recursively testing if the String is a palindrome. Something like,
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length() - 1;
return input.charAt(0) == input.charAt(len) //
&& isStringPalindrome(input.substring(1, len));
}
Is recursive without embedding a for loop. Because if you can do that, you should do something like
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length();
for (int i = 0; i <= len / 2; i++) {
if (input.charAt(i) != input.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
A simpler way to check for palindrome can be:
public static boolean isPalindrome(String s)
{ if (input == null)
return false;
else if(s.length() == 0 || s.length() == 1)
return true;
/* 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.
*/
if(s.charAt(0) == s.charAt(s.length()-1))
return isPalindrome(s.substring(1, s.length()-1));
return false;
}
Update
You are getting runtime error(NZEC) which means non-zero exit code. It means your program is ending unexpectedly. I don't see any reason except that your program doesn't have a null check. Otherwise, I have gone through your code carefully, you are doing the same thing which I have suggested.

Trying to return true if all the letters in a string are the same

What I have so far:
public boolean allSameLetter(String str)
{
for (int i = 1; i < str.length(); i++)
{
int charb4 = i--;
if ( str.charAt(i) != str.charAt(charb4))
{
return false;
}
if ( i == str.length())
{
return true;
}
}
}
Please excuse any inefficiencies if any; still relatively new to coding in general. Am I lacking some knowledge in terms of using operators and .charAt() together? Is it illogical? Or is my error elsewhere?
Using regex:
return str.matches("^(.)\\1*$");
Using streams:
str.chars().allMatch(c -> c == str.charAt(0));
Other:
return str.replace(String.valueOf(str.charAt(0), "").length() == 0;
You can follow the below steps:
(1) Get the first character (i.e., 0th index)
(2) Check the first character is the same with subsequent characters, if not return false (and comes out from method)
(3) If all chars match i.e., processing goes till the end of the method and returns true
public boolean allSameLetter(String str) {
char c1 = str.charAt(0);
for(int i=1;i<str.length;i++) {
char temp = str.charAt(i);
if(c1 != temp) {
//if chars does NOT match,
//just return false from here itself,
//there is no need to verify other chars
return false;
}
}
//As it did NOT return from above if (inside for)
//it means, all chars matched, so return true
return true;
}
As Andrew said, you are decreasing i within your for loop. You can fix this by changing it to int charb4 = i - 1;. As for making your code more efficient you could condense it down to this.
public boolean allSameLetter(String str) {
for(char c : str.toCharArray())
if(c != str.charAt(0)) return false;
return true;
}
Comment if you don't understand a part of it :)
public boolean allSameLetter(String str)
{
for (int i = 1; i < str.length() -1; i++)
{
if ( str.charAt(i) != str.charAt(i+1))
{
return false;
}
}
return true
}
-1 is there since I am checking the current value in the array, then the next value in the array, thus I need to stop a place earlier.
If the loop if statement is never entered, it will make it far enough into the code to return true
You have to create a for loop that searches through the length of the String - 1. this way the program will not crash because of a 3 letter word with the program trying to get the 4th letter. This is what works for me:
public boolean allSameLetter(String str)
{
for(int i = 0; i< str.length()-1; i++){
if (str.charAt(i) != str.charAt(i+1)){
return false;
}
}
return true;
}
if((new HashSet<Character>(Arrays.asList(s.toCharArray()))).size()==1)
return true;
return false;
This should be enough
The bug is caused by
int charb4 = i--;
this line is equal to
int charb4 = i-1;
i=i-1;
Because of this, your loop will never stop.
The easiest way to fix this
public boolean allSameLetter(String str)
{
for (int i = 1; i < str.length(); i++)
{
if ( str.charAt(i) != str.charAt(i-1))
{
return false;
}
}
}

Rewriting a for loop as recursive method?

I am having trouble rewriting the following code as a recursive method rather than using the for loop. The for loop tests to see if the String 'noSpaces' is a palindrome (the same forwards as it is backwards). The noSpaces String has no punctuation, spaces, or differences in capitalization.
Thanks for the help
public boolean isRegularPalindrome(String noSpaces) {
noSpaces = noSpaces.toUpperCase();
String[] letters = new String[noSpaces.length()];
for (int i = 0; i < letters.length; i++) {
letters[i] = Character.toString(noSpaces.charAt(i));
}
for (int i = 0; i < letters.length / 2; i++) {
if (!letters[i].equals(letters[letters.length - i - 1])) {
return false;
}
}
return true;
}
There you go:
public static boolean isPalindrome(String input) {
if (input.charAt(0) != input.charAt(input.length() - 1)) {
// Missmatch. Not a palindrome!
return false;
} else if (input.length() > 1){
// If there is more to test, continue.
return isPalindrome(input.substring(1, input.length() - 1));
} else {
// All chars were tested, or 1 char input. Palindrome!
return true;
}
}
Writing a recursive algorithm for anything requires base cases. For a palindrome, this would be a string of length 0 or length 1 -- if the string is length 0 or 1, it is a palindrome.
If the base cases aren't met, you check the first character against the last character.
If the characters aren't the same, return false.
If the characters are the same, return the recursive call to the string except for the first and last characters.
The code should look something like this.
public boolean isPalindrome(string str){
if (str.length == 0)
return true;
else if (str.length == 1)
return true;
else if(str.charAt(0) != str.charAt(str.length - 1)
return false;
else
return isPalindrome(str.substring(1, length - 1));
}

Creating a recursive method for Palindrome

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:
public static void main (String[] args){
System.out.println(isPalindrome("noon"));
System.out.println(isPalindrome("Madam I'm Adam"));
System.out.println(isPalindrome("A man, a plan, a canal, Panama"));
System.out.println(isPalindrome("A Toyota"));
System.out.println(isPalindrome("Not a Palindrome"));
System.out.println(isPalindrome("asdfghfdsa"));
}
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() == 1 ) return true;
in= in.toUpperCase();
if(Character.isLetter(in.charAt(0))
}
public static boolean isPalindromeHelper(String in){
if(in.equals("") || in.length()==1){
return true;
}
}
}
Can anyone supply a solution to my problem?
Here I am pasting code for you:
But, I would strongly suggest you to know how it works,
from your question , you are totally unreadable.
Try understanding this code. Read the comments from code
import java.util.Scanner;
public class Palindromes
{
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
// if length =0 OR 1 then it is
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
return isPal(s.substring(1, s.length()-1));
// if its not the case than string is not.
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("type a word to check if its a palindrome or not");
String x = sc.nextLine();
if(isPal(x))
System.out.println(x + " is a palindrome");
else
System.out.println(x + " is not a palindrome");
}
}
Well:
It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
In the first method, why are you testing for testing for a single space or any single character?
You might want to consider generalizing your termination condition to "if the length is less than two"
Consider how you want to recurse. One option:
Check that the first letter is equal to the last letter. If not, return false
Now take a substring to effectively remove the first and last letters, and recurse
Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.
I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.
public static boolean isPalindrome(String in){
if(in.equals(" ") || in.length() < 2 ) return true;
if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
return isPalindrome(in.substring(1,in.length-2));
else
return false;
}
Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.
I think, recursion isn't the best way to solve this problem, but one recursive way I see here is shown below:
String str = prepareString(originalString); //make upper case, remove some characters
isPalindrome(str);
public boolean isPalindrome(String str) {
return str.length() == 1 || isPalindrome(str, 0);
}
private boolean isPalindrome(String str, int i) {
if (i > str.length / 2) {
return true;
}
if (!str.charAt(i).equals(str.charAt(str.length() - 1 - i))) {
return false;
}
return isPalindrome(str, i+1);
}
Here is my go at it:
public class Test {
public static boolean isPalindrome(String s) {
return s.length() <= 1 ||
(s.charAt(0) == s.charAt(s.length() - 1) &&
isPalindrome(s.substring(1, s.length() - 1)));
}
public static boolean isPalindromeForgiving(String s) {
return isPalindrome(s.toLowerCase().replaceAll("[\\s\\pP]", ""));
}
public static void main(String[] args) {
// True (odd length)
System.out.println(isPalindrome("asdfghgfdsa"));
// True (even length)
System.out.println(isPalindrome("asdfggfdsa"));
// False
System.out.println(isPalindrome("not palindrome"));
// True (but very forgiving :)
System.out.println(isPalindromeForgiving("madam I'm Adam"));
}
}
public class palin
{
static boolean isPalin(String s, int i, int j)
{
boolean b=true;
if(s.charAt(i)==s.charAt(j))
{
if(i<=j)
isPalin(s,(i+1),(j-1));
}
else
{
b=false;
}
return b;
}
public static void main()
{
String s1="madam";
if(isPalin(s1, 0, s1.length()-1)==true)
System.out.println(s1+" is palindrome");
else
System.out.println(s1+" is not palindrome");
}
}
Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:
private static boolean isPalindrome(String str, int left, int right) {
if(left >= right) {
return true;
}
else {
if(str.charAt(left) == str.charAt(right)) {
return isPalindrome(str, ++left, --right);
}
else {
return false;
}
}
}
public static void main(String []args){
String str = "abcdcbb";
System.out.println(isPalindrome(str, 0, str.length()-1));
}
Here are three simple implementations, first the oneliner:
public static boolean oneLinerPalin(String str){
return str.equals(new StringBuffer(str).reverse().toString());
}
This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:
public static boolean isPalindrome(String str){
if(str.isEmpty()) return true;
int last = str.length() - 1;
for(int i = 0; i <= last / 2;i++)
if(str.charAt(i) != str.charAt(last - i))
return false;
return true;
}
And recursively:
public static boolean recursivePalin(String str){
return check(str, 0, str.length() - 1);
}
private static boolean check (String str,int start,int stop){
return stop - start < 2 ||
str.charAt(start) == str.charAt(stop) &&
check(str, start + 1, stop - 1);
}
public static boolean isPalindrome(String str)
{
int len = str.length();
int i, j;
j = len - 1;
for (i = 0; i <= (len - 1)/2; i++)
{
if (str.charAt(i) != str.charAt(j))
return false;
j--;
}
return true;
}
Try this:
package javaapplicationtest;
public class Main {
public static void main(String[] args) {
String source = "mango";
boolean isPalindrome = true;
//looping through the string and checking char by char from reverse
for(int loop = 0; loop < source.length(); loop++){
if( source.charAt(loop) != source.charAt(source.length()-loop-1)){
isPalindrome = false;
break;
}
}
if(isPalindrome == false){
System.out.println("Not a palindrome");
}
else
System.out.println("Pailndrome");
}
}
String source = "liril";
StringBuffer sb = new StringBuffer(source);
String r = sb.reverse().toString();
if (source.equals(r)) {
System.out.println("Palindrome ...");
} else {
System.out.println("Not a palindrome...");
}
public class chkPalindrome{
public static String isPalindrome(String pal){
if(pal.length() == 1){
return pal;
}
else{
String tmp= "";
tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));
return tmp;
}
}
public static void main(String []args){
chkPalindrome hwObj = new chkPalindrome();
String palind = "MADAM";
String retVal= hwObj.isPalindrome(palind);
if(retVal.equals(palind))
System.out.println(palind+" is Palindrome");
else
System.out.println(palind+" is Not Palindrome");
}
}
Here is a recursive method that will ignore specified characters:
public static boolean isPal(String rest, String ignore) {
int rLen = rest.length();
if (rLen < 2)
return true;
char first = rest.charAt(0)
char last = rest.charAt(rLen-1);
boolean skip = ignore.indexOf(first) != -1 || ignore.indexOf(last) != -1;
return skip || first == last && isPal(rest.substring(1, rLen-1), ignore);
}
Use it like this:
isPal("Madam I'm Adam".toLowerCase(), " ,'");
isPal("A man, a plan, a canal, Panama".toLowerCase(), " ,'");
It does not make sense to include case insensitivity in the recursive method since it only needs to be done once, unless you are not allowed to use the .toLowerCase() method.
there's no code smaller than this:
public static boolean palindrome(String x){
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
if you want to check something:
public static boolean palindrome(String x){
if(x==null || x.length()==0){
throw new IllegalArgumentException("Not a valid string.");
}
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
LOL B-]
public static boolean isPalindrome(String p)
{
if(p.length() == 0 || p.length() == 1)
// if length =0 OR 1 then it is
return true;
if(p.substring(0,1).equalsIgnoreCase(p.substring(p.length()-1)))
return isPalindrome(p.substring(1, p.length()-1));
return false;
}
This solution is not case sensitive. Hence, for example, if you have the following word : "adinida", then you will get true if you do "Adninida" or "adninida" or "adinidA", which is what we want.
I like #JigarJoshi answer, but the only problem with his approach is that it will give you false for words which contains caps.
Palindrome example:
static boolean isPalindrome(String sentence) {
/*If the length of the string is 0 or 1(no more string to check),
*return true, as the base case. Then compare to see if the first
*and last letters are equal, by cutting off the first and last
*letters each time the function is recursively called.*/
int length = sentence.length();
if (length >= 1)
return true;
else {
char first = Character.toLowerCase(sentence.charAt(0));
char last = Character.toLowerCase(sentence.charAt(length-1));
if (Character.isLetter(first) && Character.isLetter(last)) {
if (first == last) {
String shorter = sentence.substring(1, length-1);
return isPalindrome(shorter);
} else {
return false;
}
} else if (!Character.isLetter(last)) {
String shorter = sentence.substring(0, length-1);
return isPalindrome(shorter);
} else {
String shorter = sentence.substring(1);
return isPalindrome(shorter);
}
}
}
Called by:
System.out.println(r.isPalindrome("Madam, I'm Adam"));
Will print true if palindrome, will print false if not.
If the length of the string is 0 or 1(no more string to check), return true, as the base case. This base case will be referred to by function call right before this. Then compare to see if the first and last letters are equal, by cutting off the first and last letters each time the function is recursively called.
Here is the code for palindrome check without creating many strings
public static boolean isPalindrome(String str){
return isPalindrome(str,0,str.length()-1);
}
public static boolean isPalindrome(String str, int start, int end){
if(start >= end)
return true;
else
return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1);
}
public class PlaindromeNumbers {
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
/**
* Function to check a String is palindrome or not
* #param s input String
* #return true if Palindrome
*/
public boolean checkPalindrome(String s) {
if (s.length() == 1 || s.isEmpty())
return true;
boolean palindrome = checkPalindrome(s.substring(1, s.length() - 1));
return palindrome && s.charAt(0) == s.charAt(s.length() - 1);
}
Simple Solution
2 Scenario --(Odd or Even length String)
Base condition& Algo recursive(ch, i, j)
i==j //even len
if i< j recurve call (ch, i +1,j-1)
else return ch[i] ==ch[j]// Extra base condition for old length
public class HelloWorld {
static boolean ispalindrome(char ch[], int i, int j) {
if (i == j) return true;
if (i < j) {
if (ch[i] != ch[j])
return false;
else
return ispalindrome(ch, i + 1, j - 1);
}
if (ch[i] != ch[j])
return false;
else
return true;
}
public static void main(String[] args) {
System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));
}
}
for you to achieve that, you not only need to know how recursion works but you also need to understand the String method.
here is a sample code that I used to achieve it: -
class PalindromeRecursive {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String input=sc.next();
System.out.println("is "+ input + "a palindrome : " + isPalindrome(input));
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
isPalindrome(s.substring(low++,high--));
}
return true;
}
}

Categories

Resources