BudiBadu Logo

Reverse a String

Java Easy 1 views
Like0

Reversing a string is a classic programming challenge that tests your understanding of strings, characters, and basic loops in Java.

Your objective is to write a method that accepts a String and returns a new String with the characters in reverse order. In Java, String objects are immutable, meaning they cannot be changed after creation. Therefore, you cannot simply swap characters in place within the original string.

Consider using tools like StringBuilder which are designed to handle mutable sequences of characters, or manually iterating from the end to the beginning of the string to append characters.

Example 1:

Input: text = "hello"
Output: "olleh"
Explanation: The characters reversed give "olleh".

Example 2:

Input: text = "Java"
Output: "avaJ"

Constraints:

  • The length of the string will be between 0 and 1000 characters.

Algorithm Flow

Recommendation Algorithm Flow for Reverse a String - Budibadu
Recommendation Algorithm Flow for Reverse a String - Budibadu

Best Answers

java - Approach 1
public class Solution {
    public String reverseString(String text) {
        if (text == null) return null;
        return new StringBuilder(text).reverse().toString();
    }
}