Java String Reverse Solution


Problem Overview

Original Problem: Java String Reverse | HackerRank

Difficulty: Easy

Category: Strings

Description: We are given a string and our task is to determine if it is a palindrome — a word that reads the same forwards and backwards (e.g., "kayak", "level", "madam").

Understanding the Problem

We’re working with a single lowercase string and need to check if reversing it results in the same word. If so, we print "Yes"; otherwise, we print "No".

Input:

A single string, containing only lowercase letters (length ≤ 50)

Output:

One line of text

  • "Yes" if the string is a palindrome

  • "No" otherwise

Initial Reasoning

The original problem gives us template code to read the string in. From here, we can use the StringBuilder class to reverse the string and use the equals() method to determine if the original and reversed strings are identical. Based on the result, we can then print the appropriate output.

Pseudocode

// Main method:
Read the input string
Reverse the input spring 
If the two strings are equal
	Print “Yes”
Else
	Print “No”

Solution Code

// Note this is one of many possible solutions
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        String inputString= scanner.next();
        
        // Use StringBuilder to reverse the string
        String reversed = new StringBuilder(inputString).reverse().toString();
        
        // Compare the original string with the reversed string
        if (inputString.equals(reversed)) {
            System.out.println("Yes");       // It's a palindrome
        } else {
            System.out.println("No");        // Not a palindrome
        }
        
        scanner.close();
    }
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variables:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.