From 50d552d283fb02b1ae58bb3601f4b61d919c5dd4 Mon Sep 17 00:00:00 2001 From: juan Date: Tue, 12 Jul 2022 09:19:55 +0800 Subject: [PATCH] vault backup: 2022-07-12 09:19:55 --- .../Leetcode Reverse-Words-In-a-String.md | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md b/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md index e69de29..9ce5d5f 100644 --- a/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md +++ b/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md @@ -0,0 +1,83 @@ +# Leetcode Reverse-Words-In-a-String + +#### 2022-07-12 09:10 + +> ##### Algorithms: +> #algorithm #two_pointers +> ##### Data structures: +> #DS #string +> ##### Difficulty: +> #coding_problem #difficulty-easy +> ##### Additional tags: +> #leetcode +> ##### Revisions: +> N/A + +##### Related topics: +```expander +tag:#two_pointers +``` + + + +##### Links: +- [Link to problem](https://leetcode.com/problems/reverse-words-in-a-string-iii/) +___ +### Problem + +Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. + +#### Examples + +**Example 1:** + +**Input:** s = "Let's take LeetCode contest" +**Output:** "s'teL ekat edoCteeL tsetnoc" + +**Example 2:** + +**Input:** s = "God Ding" +**Output:** "doG gniD" + +#### Constraints + +- `1 <= s.length <= 5 * 104` +- `s` contains printable **ASCII** characters. +- `s` does not contain any leading or trailing spaces. +- There is **at least one** word in `s`. +- All the words in `s` are separated by a single space. + +### Thoughts + +> [!summary] +> This is a #two_pointers + +very easy and intuitive. + +### Solution + +```cpp +class Solution { + void reverse(string &s, int l, int r) { + if (l >= r) { + return; + } + swap(s[l++], s[r--]); + reverse(s, l, r); + } + +public: + string reverseWords(string s) { + int slow = 0, fast; + for (int i = 0; i < s.size(); i++) { + if (s[i] == ' ') { + fast = i - 1; + reverse(s, slow, fast); + slow = i + 1; + } + } + reverse(s, slow, s.size() - 1); + return s; + } +}; +``` \ No newline at end of file