Reverse a String in Java
Given a string, print the characters in reverse order. Solve it first using a simpleforloop without using a built-in reverse method. Then compare it with theStringBuilderapproach.
Problem
Read one line from the user and display the same string from last character to first character.
Input
WohoTechOutput
hceTohoWExamples
WohoTechhceTohoWJavaavaJmadammadamApproach Using For Loop
- Store the input string in a variable.
- Start the loop from
name.length() - 1. - Keep moving backward until index
0. - Print each character using
charAt(i).
Complexity
Time
O(n)
Extra Space
O(1)
Java String Reverse Interview Questions
- Can you reverse a string without using StringBuilder.reverse()?
- Why does the loop start from length() - 1?
- What is the time complexity of reversing a string?
- What happens if the input string is empty?
- How do you read a string character by character in Java?