-4

I am solving reverse string problem. I wonder why the helper function for swapping 2 char does not work in my code. But it works if I write the code for swapping inside the while loop.

class Solution {
    public void reverseString(char[] s) {
        
        int left = 0;
        int right = s.length - 1;
        
        while (left < right) {
            swap(s[left], s[right]);
            left++;
            right--;
        }
    }
    // not working as expected
    public void swap(char a, char b) {
        char temp = b;
        b = a;
        a = temp;
    }
}
Will
  • 1
  • Java is call-by-value. `a` and `b` are copies of what you pass in. If you change them inside of `swap`, these changes will not affect anything else than the scope of that method. Change your code so that `swap` operates on the array. – f1sh Jul 14 '22 at 14:08

1 Answers1

1

Java is call-by-value. In swap, a and b are copies of what you pass in. If you change them inside of swap, these changes will not affect anything else than in the scope of that method.

Change your swap method so that it operates on the array directly:

public void swap(char[] s, int a, in b) {
    char temp = s[b];
    s[b] = s[a];
    s[a] = temp;
}

Then call it like this:

swap(s, left, right);
f1sh
  • 11,489
  • 3
  • 25
  • 51