the input: “mnkknm” where n=0 the output: flag is always equal 1 while it should be equal 3 and it returns -1 what is the problem ? note : palindrome means for example if the Reverse of malayalam is also malayalam then its palindrome another note : i should write the code recursive as it’s a homework
public static int PalindromeCheck(String x , int n) { int flag =0; if (n+1 !=x.length()/2) { char s = x.charAt(n); char y = x.charAt(x.length()-1-n); if (s==y) { flag++; System.out.println(flag); // i write it to check the value of the flag } return flag+PalindromeCheck(x,n+1) ; } if (flag==x.length()/2) { return 1;} else{ return -1; }
Advertisement
Answer
try this method please
public static boolean isPal(String s) { if(s.length() == 0 || s.length() == 1) { return true; } if(s.charAt(0) == s.charAt(s.length()-1)) { return isPal(s.substring(1, s.length() - 1)); } return false; }