---
description: '# Easy'
---

# 557. Reverse Words in a String III

{% hint style="danger" %}
string can't be modified but can use index

`[::-1]` is to reverse a list
{% endhint %}

{% tabs %}
{% tab title="Python" %}
```java
class Solution:
    def reverseWords(self, s: str) -> str:
        if len(s) <= 1:
            return s
        
        l = s.split()
        s = ''
        for i in l:
            s = s + i[::-1] + ' '
        return s[:-1]
```
{% endtab %}

{% tab title="Java (use StringBuilder, O(N))" %}
```java
// Some code
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder res = new StringBuilder();
        for(String word: words) {
            StringBuilder re_word = new StringBuilder(word);
            res.append(re_word.reverse().toString() + " ");
        }
        return res.toString().trim();
    }
}
```
{% endtab %}

{% tab title="Java (slow, self-define functions)" %}
```java
// Some code
class Solution {
    public String reverseWords(String s) {
        String[] words = split(s);
        StringBuilder res = new StringBuilder();
        for(String word: words) {
            res.append(reverse(word) + " ");
        }
        return res.toString().trim();
    }
    
    public String[] split(String s) {
        ArrayList < String > words = new ArrayList < > ();
        StringBuilder word = new StringBuilder();
        for(int i = 0; i < s.length(); i ++) {
            if(s.charAt(i) == ' ') {
                words.add(word.toString());
                word = new StringBuilder();
            } else
                word.append(s.charAt(i));
        }
        words.add(word.toString());
        return words.toArray(new String[words.size()]);
    }
    
    public String reverse(String s) {
        StringBuilder res = new StringBuilder();
        for(int i = 0; i < s.length(); i ++) {
            res.insert(0, s.charAt(i));
        }
        return res.toString();
    }
}
```
{% endtab %}
{% endtabs %}
