# 151. Reverse Words in a String

{% embed url="<https://leetcode.com/problems/reverse-words-in-a-string/>" %}

{% tabs %}
{% tab title="Python" %}

```python
class Solution:
    def reverseWords(self, s: str) -> str:
        words=[x for x in s.split(' ') if x != '']
        new_str = ''
        for n in range(len(words)):
            new_str += words[len(words)-n-1]
            if n != len(words)-1:
                new_str += ' '
        return new_str
```

{% endtab %}

{% tab title="Java" %}

```java
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        
        StringBuilder res = new StringBuilder();
        
        for (int i=words.length-1; i>=0; i--) {
            String w = words[i];
            if (!w.isEmpty()) {
                res.append(words[i]).append(" ");
            }
        }
        return res.toString().trim();
    }
}
```

{% endtab %}
{% endtabs %}
