> For the complete documentation index, see [llms.txt](https://ucan.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ucan.gitbook.io/notes/two-pointers/151.-reverse-words-in-a-string.md).

# 151. Reverse Words in a String

```java
class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int endIndex = -1;
        for (int i = s.length()-1; i>=0; i--){
            if(s.charAt(i)!=' ' && endIndex==-1){
                endIndex = i;
                // key: do not change i in case if this is a single character word
                i++;
            }else if(s.charAt(i)!=' ' && endIndex>=0 && (i==0 || s.charAt(i-1)==' ')){
                sb.append(s.substring(i, endIndex+1)+' ');
                endIndex=-1;
            }
        }
        sb.setLength(sb.length()-1);
        return sb.toString();
    }
}
```
