Question

Formatted question description: https://leetcode.ca/all/344.html

 344	Reverse String

 Write a function that takes a string as input and returns the string reversed.

 Example:
 Given s = "hello", return "olleh".

 @tag-string
 @tag-2pointers

Algorithm

Go from both ends to the middle while swapping characters on both sides.

Code

Java

public class Reverse_String {

    class Solution {
        public void reverseString(char[] s) {

            int l = 0;
            int r = s.length - 1;

            while (l < r) {
                char tmp = s[l];
                s[l] = s[r];
                s[r] = tmp;
                l++;
                r--;
            }
        }
    }

    class Solution_cheat {
        public String reverseString(String input) {

            StringBuilder s = new StringBuilder(input);
            s.reverse();

            return s.toString();
        }
    }
}

All Problems

All Solutions