Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class Palindromes
  3. {
  4.  
  5.     public static boolean isPal(String s)
  6.     {
  7.         if(s.length() == 0 || s.length() == 1)
  8.             // if length =0 OR 1 then it is
  9.             return true;
  10.         if(s.charAt(0) == s.charAt(s.length()-1))
  11.             // check for first and last char of String:
  12.             // if they are same then do the same thing for a substring
  13.             // with first and last char removed. and carry on this
  14.             // until you string completes or condition fails
  15.             return isPal(s.substring(1, s.length()-1));
  16.  
  17.         // if its not the case than string is not.
  18.         return false;
  19.     }
  20.  
  21.     public static void main(String[]args)
  22.     {
  23.         Scanner sc = new Scanner(System.in);
  24.         System.out.println("type a word to check if its a palindrome or not");
  25.         String x = sc.nextLine();
  26.         if(isPal(x))
  27.             System.out.println(x + " is a palindrome");
  28.         else
  29.             System.out.println(x + " is not a palindrome");
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement