3
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }


    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the entire code a couple of times but there seems to be an issue.

Input : "Let's take LeetCode contest" my answer: " s'teL ekat s'teL edoCteeL ekat s'teL " correct answer: "s'teL ekat edoCteeL tsetnoc" whats going on?

Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31

5 Answers5

3

There are several problems:

  • You set current to the current position, and then iterate down to 0 append characters. Instead of going down to 0, you iterate until the beginning of the last word. Alternative, iterate until the previous ' ' character.

  • You only append something after seeing a ' ' character. What will happen at the end of the sentences? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed.

A simpler approach is to take advantage of the StringBuilder's ability to insert characters at some position. You could track the beginning position of the current word, and as you iterate over the characters, insert if it's not ' ', or else append a ' ' and reset the insertion position.

StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == ' ') {
        build.append(' ');
        current = i + 1;
    } else {
        build.insert(current, c);
    }
}
return build.toString();
janos
  • 120,954
  • 29
  • 226
  • 236
1

Use a StringBuilder to reverse each word in your String :

 String input = "Let's take LeetCode contest";

    String[] split = input.split(" +");
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < split.length; i++) {

        output.append(new StringBuilder(split[i]).reverse());
        if(i<input.length()-1)
        output.append(" ");
    }

    System.out.println(output);
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21
1

First, you skip over index 0. Put these lines at the end of your method to avoid this:

count++; 
current = count;

You might need a variable to track where the current word began. For example, declare one along with count and current like this:

int wordStart = 0;

Then, when you finish processing a word, set wordStart to point to the first character of the next word. I would put that after the while loop, here:

build.append(s.charAt(i));
wordStart = count + 1;

You will also need to change this: while(current > 0){ to this: while(current >= wordStart)

Also: you don't need count. The variable i is the exact same thing.

Keara
  • 589
  • 1
  • 6
  • 17
1

You can use stream-api for your goal:

Stream.of(str.split(" "))
            .map(s -> new StringBuilder(s).reverse().toString())
            .reduce((s1, s2) -> s1 + " " + s2)
            .orElse(null);
yanefedor
  • 2,132
  • 1
  • 21
  • 37
  • 1
    `.reduce((s1, s2) -> s1 + " " + s2).orElse(null);` can be simplified with `collect(Collectors.joining(" "))` – Pshemo Dec 07 '17 at 18:55
-1

This is the easy way:

return Arrays.stream(s.split(" " ))
        .map(StringBuilder::new)
        .map(StringBuilder::reverse)
        .map(StringBuilder::toString)
        .collect(Collectors.joining(" "));
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I removed my comment then (can't remove downvote since it wasn't mine). I am upvoting only answers here which actually address "I am having trouble understanding why this doesn't work". Without that question would be duplicate of many other questions line: [Reverse each individual word of “Hello World” string with Java](https://stackoverflow.com/q/2441501) – Pshemo Dec 07 '17 at 19:00