-3

Below mentioned code is for reversing k elements in a string of n size. Line 3 is returning garbage value. Can anyone please help me out on this.

class Solution{
     public String reverseStr(String s, int k){
        char[] ch = s.toCharArray();
        Stack<Character> st = new Stack();
         int i;
        for(i = 0; i < k; i++){
            st.push(ch[i]);
        }
         i = 0;
         while(!st.isEmpty()){
             ch[i] = st.pop();
         }
         return ch.toString();
     }
}
  • 2
    What do you mean by "garbage value"? – enzo Jul 31 '21 at 21:34
  • Give an example of your input and output strings. – Basil Bourque Jul 31 '21 at 21:34
  • The [Answer by Jesper](https://stackoverflow.com/a/68605994/642706) is correct and should be accepted for fixing your specific problem. However, such code using `char` is obsolete. The `char` type is unable to represent even half of the characters defined by Unicode and supported by Java. Instead, learn to use Unicode [code point](https://en.wikipedia.org/wiki/Codepoint) integers. see my version of your code adapted to code points [run live at IdeOne.com](https://ideone.com/0PfqWc). My code handles an input of `"dog"` whereas your code breaks. – Basil Bourque Jul 31 '21 at 22:16

1 Answers1

3

Increment i

There is a mistake in this part of your code:

i = 0;
while(!st.isEmpty()){
    ch[i] = st.pop();
}

Note that i remains 0 the whole time, so you are assigning to ch[0] in each iteration of the loop. You probably meant to increment i in the loop:

i = 0;
while(!st.isEmpty()){
    ch[i++] = st.pop();
}

Generate String from char array

Note that the last line of your code:

return ch.toString();

will not return what you expect. If you want to convert the char array to a String containing the characters, do this instead:

return new String(ch);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Jesper
  • 202,709
  • 46
  • 318
  • 350