0

I am trying a leetcode question on reversing the string. I don't understand why my solution is not working. Can anyone code review it please?

class Solution {
    public char[] reverseString(char[] s) {
        char[] temp = new char[s.length];

        int index = s.length - 1;

        for (int i = 0; i < s.length; ++i){
            temp[i] = s[index--];
        }

        return temp;
    }
}

Leetcode says my output is ["h", "e", "l", "l", "o"] when the output should be ["o", "l", "l", "e", "h"]. Thanks for the help.

1
  • 2
    works for me assuming that s == 'hello' Commented Feb 5, 2020 at 2:55

1 Answer 1

2

Your solution does return an array with the characters in reverse order, but it would appear they assume you will do it in-place (and test accordingly). Iterate half of the array, and swap the current character with the index offset from the length. Like,

public char[] reverseString(char[] s) {
    for (int i = 0; i < s.length / 2; ++i) {
        char temp = s[i];
        s[i] = s[s.length - i - 1];
        s[s.length - i - 1] = temp;
    }
    return s;
}

If that is not correct, please carefully review all of the requirements posted (and share them here).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.