-5

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"]

class Solution {
    public void reverseString(char[] s) {
        for(int i=0; i<s.length/2; i++){
            for(int j=s.length-1; j>i; j--){
               char temp = s[j];
                s[j] = s[i];
                s[i] = temp;

            }
        }
    }
}

Input: ["h","e","l","l","o"]

My output["e","l","o","h","l"]

expected: ["o","l","l","e","h"]

Can anyone tell where am I wrong.

TIGUZI
  • 231
  • 1
  • 3
  • 12

2 Answers2

4

You added an inner loop, "j" should be calculated based on the length of the array and i in one loop. Like,

for (int i = 0; i < s.length / 2; i++) {
    char temp = s[s.length - i - 1];
    s[s.length - i - 1] = s[i];
    s[i] = temp;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • So we can't use inner loop to solve this problem? – TIGUZI Nov 12 '19 at 03:06
  • You only want to swap one character of `s` per iteration of the "outer loop"; using an inner loop makes that difficult - since you would be swapping each character at `i` with multiple positions from `j` (hence your current scrambled output). – Elliott Frisch Nov 12 '19 at 03:17
1

you can fix with add i++; the full code like this,

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

bt, i dont like this write style ....

doubleevil
  • 41
  • 2
  • What you added is exactly what I wonder to know sir. Why we have to add i++there? I mean the int ' i ' should be increased automatically by one in next round, why we need add i++ in the inner loop..............Look, the first round i=0 and I swap a[0] with a[4],,then in the next round i = 1, then j=3 and we exchange a[1] with a[3]. – TIGUZI Nov 12 '19 at 03:23