Reverse String

Problem

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is a printable ascii character.

Solution

class Solution {
    public void reverseString(char[] s) {
        for (var i = 0; i < (int) Math.floor(s.length / 2); i++) {
            var dst = s.length - 1 - i;
            var tmp = s[i];
            s[i] = s[dst];
            s[dst] = tmp;
        }
    }
}

Recent posts from blogs that I like

American in Paris, the brief paintings of Susan Watkins

She started training at the age of 15 in New York, then in Paris, where for a decade she was one of the most successful American painters, but died soon after her return to the USA.

via The Eclectic Light Company

You should all be asking way more questions

When someone is explaining something to me, I ask on average one question every thirty seconds. I’m sure this is frustrating to some people, but it’s actually a good habit and you should do it too.

Trying to understand

Most of the questions I ask are very short, and require very short answers. Typic...

via Sean Goedecke

The hyperlocal

Notes on art, machine intelligence, and paying attention to one’s immediate environment

via Henrik Karlsson