Reverse a String in Java - The Coding Shala
Home >> Interview Questions >> Reverse a String
Method 2:
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; while(i<j){ char tmp = s[i]; s[i] = s[j]; s[j] = tmp; i++; j--; } } }
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
Comments
Post a Comment