Reverse a String | String Problem | LeetCode 344
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a String as an array of Characters, reverse the string by modifying the input array. Implement the problem in O(1) extra memory.
Example
Input :- ["h", "e", "l", "l", "o"] Output :- ["o", "l", "l", "e", "h"]
Input :- ["m", "o", "r", "n", "i", "n", "g"] Output :- ["g", "n", "i", "n", "r", "o", "m"]
Solution
This problem can be solved in following steps :-
- Create three variables first pointing to index 0, second pointing to last index (n-1, where n is the length of an array) and temp.
- Copy the character at first variable to temp, the character at second variable to first and character at temp variable to second.
- Move the first variable to right and second variable to left.
- Repeat steps 2 and 3, until first is less than second.
Program
public class Main { public static void main(String[] args) { Main main = new Main(); char[] array = "morning".toCharArray(); main.reverseString(array); System.out.print(String.valueOf(array)); } /* Solution */ public void reverseString(char[] s) { int first = 0; int last = s.length - 1; char c; while(first<last){ c = s[last]; s[last] = s[first]; s[first] = c; first++; last--; } } }
Result
gninrom
Similar Post
That’s all for Reverse a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.