Saturday, May 18, 2019

How do you check palindrome?

Problem statement:
How do you check palindrome?
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         isPalindrome(s);
  5.     }
  6.     public static void isPalindrome(String s) {
  7.         String rev = "";
  8.         char c[] = s.toCharArray();
  9.         for (int i = s.length() - 1; i >= 0; i--) {
  10.             rev = rev + c[i];
  11.         }
  12.         if (s.equals(rev))
  13.             System.out.println("Yes");
  14.         else
  15.             System.out.println("No");
  16.     }
  17. }
Output:
Yes
Mehod-II:
  1. public class Palindrome {
  2.     public static void main(String[] args) {
  3.         String s = "madam";
  4.         System.out.println(isPalindrome(s) ? "Yes" : "No");
  5.     }
  6.     public static boolean isPalindrome(String s) {
  7.         int p = s.length() - 1;
  8.         boolean flag = true;
  9.         char c[] = s.toCharArray();
  10.         for (int i = 0; i < s.length() / 2; i++) {
  11.             if (c[i] != c[p]) {
  12.                 flag = false;
  13.                 break;
  14.             }
  15.             p--;
  16.         }
  17.         return flag;
  18.     }
  19. }
Output:
Yes

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...