---
# System prepended metadata

title: 0186. Reverse Words in a String II
tags: [Leetcode, Medium, Microsoft]

---

# 0186. Reverse Words in a String II
###### tags: `Leetcode` `Microsoft` `Medium`
Link: https://leetcode.com/problems/reverse-words-in-a-string-ii/
## 思路
先reverse所有，再分别reverse每个单词，最后reverse最后一个单词
## Code
```java=
class Solution {
    public void reverseWords(char[] s) {
        reverse(s, 0, s.length-1);
        int l = -1;
        for(int i = 0;i < s.length;i++){
            if(s[i]==' '){
                reverse(s, l+1, i-1);
                l = i;
            }
        }
        reverse(s, l+1, s.length-1);
    }
    private void reverse(char[] s, int start, int end){
        int l = start;
        int r = end;
        while(l<r){
            char temp = s[l];
            s[l] = s[r];
            s[r] = temp;
            l++;
            r--;
        }
    }
}
```