Monday, November 7, 2016

Reverse String

Question:
Write a function that takes a string as input and returns the string reversed.
(Reference: https://leetcode.com/problems/reverse-string/)

Solution:
Let's take a couple of example to check the input and expected output of the given problem.
Example 1:
Input: "johny"
Output: "ynhoj"

Example 2:
Input: ""trump"
Output: "pmurt"

Solution 1:
Using String Builder:

    public String reverseString(String s) {
        if (s == null || s.length() <= 1) {
            return s;
        }
        StringBuilder sb = new StringBuilder();
        int len = s.length();
        for(int i = 0; i < len; i++) {
            sb.insert(0, s.charAt(i));
        }
        
        return sb.toString();
    }

Solution 2:

Using character array:

    public String reverseString(String s) {
        if (s == null || s.length() <= 1) {
            return s;
        }
        char[] arr = s.toCharArray();
        for(int i = 0; i < arr.length/2; i++) {
            char c = arr[i];
            arr[i] = arr[arr.length-1-i];
            arr[arr.length-1-i] = c;
        }
        
        return String.valueOf(arr);
    }

Please do let me know your comments about this blog post.

Thanks. Happy Coding :)

No comments:

Post a Comment