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 

Reverse a String

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 :-

  1. 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.
  2. Copy the character at first variable to temp, the character at second variable to first and character at temp variable to second.
  3. Move the first variable to right and second variable to left.
  4. 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

  1. Reverse Word in String
  2. First Unique Character in a String
  3. Reverse Vowels of a String

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.