Reverse a String

beginner Strings

Problem

Read one line of text and print it reversed.

Constraints

  • 1 <= length <= 10^5, ASCII text

Examples

Input

hello

Output

olleh

Solutions

Best approachTime O(n)Space O(n)

We read the characters from the last index to the first index and collect them. A StringBuilder is faster than adding to a String again and again.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Reverse the text.
 * Input   : One line of text.
 * Output  : The reversed text.
 * Approach: Read the characters from the end.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(String s) {
        // Step 1: Build the answer in a StringBuilder.
        StringBuilder result = new StringBuilder();

        // Step 2: Go from the last character to the first one.
        for (int i = s.length() - 1; i >= 0; i--) {
            // Step 3: Add the character to the answer.
            result.append(s.charAt(i));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.hasNextLine() ? scanner.nextLine() : "";
        System.out.println(solve(s));
    }
}
Hints (1)
  1. Which index is the last character?