Tuesday, May 14, 2019

Java String Reverse

Problem statement:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Given a string , print Yes if it is a palindrome, print No otherwise
Constraints:
A will consist at most 50 lower case english letters.
Sample Input:
madam
Sample Output:
Yes
  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.         for (int i = 0; i < s.length() / 2; i++) {
  10.             if (s.charAt(i) != s.charAt(p)) {
  11.                 flag = false;
  12.                 break;
  13.             }
  14.             p--;
  15.         }
  16.         return flag;
  17.     }
  18. }
Output:
Yes
Method-II:
  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.         for (int i = s.length() - 1; i >= 0; i--) {
  9.             rev = rev + s.charAt(i);
  10.         }
  11.         if (s.equals(rev))
  12.             System.out.println("Yes");
  13.         elset a Palindrome");
  14.     }
  15. }
Output: 
Yes

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...