# LeetCode 557: Reverse Words in a String III

## Problem Restatement

We are given a string `s`.

The string contains words separated by single spaces.

We need to reverse the characters inside each word while keeping:

1. The word order unchanged.
2. The spaces in the same positions.

The problem guarantees there are no leading or trailing spaces, and words are separated by exactly one space. ([github.com](https://github.com/doocs/leetcode/blob/main/solution/0500-0599/0557.Reverse%20Words%20in%20a%20String%20III/README_EN.md?utm_source=chatgpt.com))

## Input and Output

| Item | Meaning |
|---|---|
| Input | A string `s` |
| Output | A string with each word reversed |
| Keep unchanged | Word order |
| Keep unchanged | Space positions |

Example function shape:

```python
def reverseWords(s: str) -> str:
    ...
```

## Examples

Example 1:

```python
s = "Let's take LeetCode contest"
```

Reverse each word individually:

| Original | Reversed |
|---|---|
| `"Let's"` | `"s'teL"` |
| `"take"` | `"ekat"` |
| `"LeetCode"` | `"edoCteeL"` |
| `"contest"` | `"tsetnoc"` |

The final answer is:

```python
"s'teL ekat edoCteeL tsetnoc"
```

Example 2:

```python
s = "God Ding"
```

Reverse each word:

```python
"doG gniD"
```

## First Thought: Split Into Words

The most direct idea is:

1. Split the string by spaces.
2. Reverse every word.
3. Join the words back together with spaces.

For example:

```python
s.split()
```

turns:

```python
"God Ding"
```

into:

```python
["God", "Ding"]
```

Then we reverse each word and join them again.

This solution is already efficient enough for the problem constraints.

## Key Insight

We do not need to change the structure of the sentence.

Only the characters inside each word need to be reversed.

The spaces remain fixed.

So each word can be processed independently.

## Algorithm

1. Split the string into words.
2. Reverse every word using slicing:
   ```python id="smnq9u"
   word[::-1]
   ```
3. Join the reversed words using spaces.

## Correctness

The algorithm processes every word independently.

For each word, the expression:

```python
word[::-1]
```

returns the characters of the word in reverse order.

The list of words remains in the original order because the algorithm never reorders the words themselves.

Finally, joining the reversed words using single spaces reconstructs the sentence with exactly one space between adjacent words.

Therefore:

1. Every word is reversed correctly.
2. The word order is preserved.
3. The spacing structure is preserved.

So the algorithm produces exactly the required output.

## Complexity

Let `n` be the length of `s`.

| Metric | Value | Why |
|---|---|---|
| Time | `O(n)` | Every character is processed a constant number of times |
| Space | `O(n)` | The output string and temporary word list require linear space |

## Implementation

```python
class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(word[::-1] for word in s.split())
```

## Code Explanation

We first split the sentence into words:

```python
s.split()
```

Then we reverse every word:

```python
word[::-1]
```

The slice syntax with step `-1` walks through the string backward.

Finally:

```python
" ".join(...)
```

joins the reversed words back into one sentence using spaces.

## Two-Pointer Version

We can also solve the problem manually without using `split()`.

This version scans the string directly.

```python
class Solution:
    def reverseWords(self, s: str) -> str:
        chars = list(s)
        n = len(chars)

        start = 0

        for end in range(n + 1):
            if end == n or chars[end] == " ":
                left = start
                right = end - 1

                while left < right:
                    chars[left], chars[right] = chars[right], chars[left]
                    left += 1
                    right -= 1

                start = end + 1

        return "".join(chars)
```

This version reverses each word in place inside the character array.

## Testing

```python
def run_tests():
    s = Solution()

    assert s.reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc"
    assert s.reverseWords("God Ding") == "doG gniD"
    assert s.reverseWords("a") == "a"
    assert s.reverseWords("ab cd") == "ba dc"
    assert s.reverseWords("Python") == "nohtyP"

    print("all tests passed")

run_tests()
```

| Test | Why |
|---|---|
| `"Let's take LeetCode contest"` | Official-style example |
| `"God Ding"` | Multiple short words |
| `"a"` | Single-character word |
| `"ab cd"` | Two small words |
| `"Python"` | Single full-word input |

