344. Reverse String

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

Example:

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

Thought

i →               ← j
h    e    l    l    o                   

exchange i with j in each iteration.

Solution

public class Solution {
    public String reverseString(String s) {
        char[] c = s.toCharArray();
        int i = 0, j = c.length - 1;
        while (i < j) {
            char t = c[i];
            c[i++] = c[j];
            c[j--] = t;
        }
        return String.valueOf(c);
    }
}

results matching ""

    No results matching ""