Reverse String

Problem

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

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

Solution

Built-in method with StringBuilder

public class Solution {
    public String reverseString(String s) {
        if (s == null || s.length() <= 1) return s;
        return new StringBuilder(s).reverse().toString();
    }
}

Using swap in char array

public class Solution {
    public String reverseString(String s) {
        if (s == null || s.length() <= 1) return s;
        char[] chars = s.toCharArray();
        int left = 0, right = chars.length - 1;
        while (left < right) {
            char temp = chars[left];
            chars[left++] = chars[right];
            chars[right--] = temp;
        }
        return new String(chars);
    }
}

Analysis

In this problem, we have two approaches
One is using the StringBuilder and its built-in method reverse()
The other one is to swap two character using two pointers

results matching ""

    No results matching ""