From 6f2560408b3554d64d0a5d79456e6e7412611436 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Mon, 8 Nov 2021 19:34:36 +0000 Subject: [PATCH] reverse-words-in-a-string-iii --- reverse-words-in-a-string-iii/sol.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 reverse-words-in-a-string-iii/sol.go diff --git a/reverse-words-in-a-string-iii/sol.go b/reverse-words-in-a-string-iii/sol.go new file mode 100644 index 0000000..ac69424 --- /dev/null +++ b/reverse-words-in-a-string-iii/sol.go @@ -0,0 +1,22 @@ +package main + +func reverseWords(s string) string { + l := len(s) + out := make([]rune, l) + word := make([]rune, 0) + for idx, char := range s { + if char == ' ' { + for widx, wchar := range word { + out[idx-widx-1] = wchar + } + out[idx] = ' ' + word = word[:0] + } else { + word = append(word, char) + } + } + for widx, wchar := range word { + out[l-widx-1] = wchar + } + return string(out) +}