# 557.Reverse-Words-in-a-String-III

## 557. Reverse Words in a String III

## 题目地址

<https://leetcode.com/problems/reverse-words-in-a-string-iii/>

## 题目描述

```
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
```

## 代码

### Approach 1:

```java
public class Solution {
  public String reverseWords(String s) {
    String words[] = s.split(" ");
    StringBuilder res = new StringBuilder();
    for (String word: words) {
      res.append(new StringBuffer(word).reverse().toString() + " ");
    }
    return res.toString().trim();
  }
}
```

### Approach #2 Without using pre-defined split and reverse function

```java
public 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();
    }
}
```

### Approach #3 Using StringBuilder and reverse method

```java
public class Solution {
    public String reverseWords(String input) {
        final StringBuilder result = new StringBuilder();
        final StringBuilder word = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) != ' ') {
                word.append(input.charAt(i));
            } else {
                result.append(word.reverse());
                result.append(" ");
                word.setLength(0);
            }
        }
        result.append(word.reverse());
        return result.toString();
    }
}
```
