-2

Here is the code:

class Solution {
    public void reverseString(char[] s) {
        int j = s.length-1;
        System.out.print("[");
        char ch = '"';
        for(int i = j; i >= 0 ; i--)
        {
            System.out.print(ch);
            System.out.print(s[i]);
            System.out.print(ch);
            System.out.print(",");
        }
        System.out.print("]");
    }
}

Your input
["h","e","l","l","o"]

my output:
stdout
["o","l","l","e","h",]

Expected
["o","l","l","e","h"]

I just want to remove the extra , (comma) from my output. what should I do or change?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Don't print in your loop. First reverse the `char[] s` (and don't call it `s`, call it `input`, the computer doesn't care what you call it, but humans that need to read your code do) to a new `char[] output` of the same length as your input. Then print _that_ when you're done. – Mike 'Pomax' Kamermans Apr 14 '21 at 16:30
  • 1
    Don't print the comma when `i == 0`, i.e. add `if (i != 0)` before the `print(",")` statement. – Andreas Apr 14 '21 at 16:33

3 Answers3

0

You need to break loop when end of Array is reached. before printing comma, check to see if current element is 0 and if it is break the loop otherwise print ','.

ringadingding
  • 475
  • 5
  • 14
0

You can reverse the input array and then using String.join

References:

How to reverse?

Example of String.join

zwlxt
  • 301
  • 2
  • 9
0

You are printing a comma after every entry in your loop, which gives you a comma after the last entry. Instead print a comma before every entry except the first:

 for(int i = j; i >= 0 ; i--)
 {
     // No comma before first output entry.
     if (i != j)
     {
         System.out.print(",");
     }
     System.out.print(ch);
     System.out.print(s[i]);
     System.out.print(ch);
 }

It is generally easier to detect the first entry in a list, array, stream etc. than the last entry, which may require read-ahead or some extra complication. Detecting the first entry is as simple as a boolean flag or similar.

rossum
  • 15,344
  • 1
  • 24
  • 38