Reverse a String in Java - The Coding Shala

Home >> Interview Questions >> Reverse a String

Reverse a String in Java

In the following post, we will see how to reverse a string in Java. Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ASCII characters.

Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Reverse a String in Java Program

Method 1:
We can reverse a string using two pointers.
Java code:
class Solution {
    public void reverseString(char[] s) {
        int i = 0;
        int j = s.length-1;
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;

Method 2:
We can reverse a string using recursion.
Java Code:
class Solution {
    public void reverseString(char[] s) {
        String str = new String(s);
        str = reverse(str);
        for(int i =0; i<str.length(); i++) s[i] = str.charAt(i);
    public String reverse(String str){
        int length = str.length();
        if (length <= 1) return str;
        String leftStr = str.substring(0, length / 2);
        String rightStr = str.substring(length / 2, length);
        return (reverse(rightStr) + reverse(leftStr));

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

First Unique Character in a String Java - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala