Java String Reverse - Hacker Rank Solution

Java String Reverse - Hacker Rank Solution

Hello Friends, How are you? Today I am going to solve the HackerRank Java String Reverse Problem with a very easy explanation. This is the 17th problem of Java on HackerRank. In this article, you will get more than one approach to solving this problem. So let's start-

{tocify} $title={Table of Contents}

Java String Reverse - Hacker Rank Solution

HackerRank Java String Reverse - Problem Statement

A palindrome is a word, phrase, number, or other sequences of characters that reads the same backwards or forward.

Given a string A, print Yes if it is a palindrome, print No otherwise.

Constraints

  •  A will consist of at most 50 lower case English letters.

Sample Input

madam {codeBox}

Sample Output

Yes {codeBox}

Java String Reverse - Hacker Rank Solution

Approach I:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        /* Read input */
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        scan.close();
        
        /* Reverse string and compare to original */
        /* If a String is equivalent to itself when reversed, it's a palindrome */
        
        String reversed = new StringBuilder(str).reverse().toString();
        System.out.println(str.equals(reversed) ? "Yes" : "No");
    }
}


Approach II:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        
        
        if(A.equalsIgnoreCase(new StringBuffer(A).reverse().toString()))
            System.out.println("Yes");
        else
            System.out.println("No");
        
    }
}


Approach III:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        /* Enter your code here. Print output to STDOUT. */
        String rev = "";
        for(int i=A.length()-1;i>=0;i--)
            rev+=A.charAt(i);
        if(rev.equals(A))
            System.out.println("Yes");
        else
                    System.out.println("No");

    }
}


Disclaimer: The above Problem ( Java String Reverse ) is generated by Hackerrank but the Solution is Provided by MyEduWaves. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the contact form.

I hope you have understood the solution to this HackerRank Problem. All these three solutions will pass all the test cases. Now visit Java String Reverse HackerRank Problem and try to solve it again.

All the Best!

Post a Comment

Previous Post Next Post