Reverse String

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"]
 
class Solution {
    public void reverseString(char[] s) {
       int start = 0, end = s.length-1;
        while(start  < end){
            char temp = s[end];
            s[end] = s[start];
            s[start] = temp;
            start++;
            end--;
        }
    }
}


Here, we are going to solve using two pointer concept.
1) In above solution, start and end act as two pointer such that start iterates from beginning and end variable iterates from end.
2) For each iteration store the end character in temp variable and store start value to end and finally temp value to start.
3) Increment start by 1 and decrement end by 1.
4) Repeat above steps until start < end condition fails.


Click Follow button to receive updates from us instantly.

Please let us know about your views in comment section.

Happy Coding...😍

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II