From 0d8e2de00218fd3007f02687278cf8bbff3914b3 Mon Sep 17 00:00:00 2001 From: Techmonite <150219021+Starlaps-365@users.noreply.github.com> Date: Mon, 22 Jul 2024 17:06:38 +0200 Subject: [PATCH] Update 186. Reverse Words in a String II.cpp To reverse the words in a character array s in-place, we can follow these steps: Reverse the entire character array. Reverse each word in the reversed array. --- 186. Reverse Words in a String II.cpp | 33 +++++++++++++++++---------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/186. Reverse Words in a String II.cpp b/186. Reverse Words in a String II.cpp index 7200ef5..17954e1 100644 --- a/186. Reverse Words in a String II.cpp +++ b/186. Reverse Words in a String II.cpp @@ -1,18 +1,27 @@ class Solution { public: - void reverse(int begin, int end, string &s){ - while(begin < end) - swap(s[begin++], s[end--]); - } - void reverseWords(string &s) { - const size_t n = s.length(); - reverse(0, n - 1, s); - int i, j; - for(i = 0, j = 0; j <= n; ++j){ - if(j == n || s[j] == ' '){ - reverse(i, j - 1, s); - i = j + 1; + void reverseWords(vector& s) { + // Step 1: Reverse the entire character array + reverse(s.begin(), s.end()); + + // Step 2: Reverse each word in the reversed array + int start = 0; + for (int i = 0; i < s.size(); ++i) { + if (s[i] == ' ') { + reverse(s.begin() + start, s.begin() + i); + start = i + 1; } } + + // Reverse the last word + reverse(s.begin() + start, s.end()); + } + + void reverse(vector& s, int i, int j) { + while (i < j) { + swap(s[i], s[j]); + i++; + j--; + } } };