> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/wan-quan-an-zhao-jiu-zhang-suan-fa-shua-de-60-dao-zuo-you/ii.-sorted-array/557.-reverse-words-in-a-string-iii.md).

# 557. Reverse Words in a String III

\# Easy

{% 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 %}
