From d542d1a670e2af3c79634952ce5b5301f8018247 Mon Sep 17 00:00:00 2001 From: openset Date: Wed, 27 Feb 2019 14:26:18 +0800 Subject: [PATCH] Add: Reverse Words in a String --- .../reverse_words_in_a_string.go | 14 +++++++++ .../reverse_words_in_a_string_test.go | 30 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/problems/reverse-words-in-a-string/reverse_words_in_a_string.go b/problems/reverse-words-in-a-string/reverse_words_in_a_string.go index 92807538a..92d8ecc55 100644 --- a/problems/reverse-words-in-a-string/reverse_words_in_a_string.go +++ b/problems/reverse-words-in-a-string/reverse_words_in_a_string.go @@ -1 +1,15 @@ package reverse_words_in_a_string + +import ( + "regexp" + "strings" +) + +func reverseWords(s string) string { + reg := regexp.MustCompile(`\S+`) + words := reg.FindAllString(s, -1) + for i, j := 0, len(words)-1; i < j; i, j = i+1, j-1 { + words[i], words[j] = words[j], words[i] + } + return strings.Join(words, " ") +} diff --git a/problems/reverse-words-in-a-string/reverse_words_in_a_string_test.go b/problems/reverse-words-in-a-string/reverse_words_in_a_string_test.go index 92807538a..8959e1202 100644 --- a/problems/reverse-words-in-a-string/reverse_words_in_a_string_test.go +++ b/problems/reverse-words-in-a-string/reverse_words_in_a_string_test.go @@ -1 +1,31 @@ package reverse_words_in_a_string + +import "testing" + +type caseType struct { + input string + expected string +} + +func TestReverseWords(t *testing.T) { + tests := [...]caseType{ + { + input: "the sky is blue", + expected: "blue is sky the", + }, + { + input: " hello world! ", + expected: "world! hello", + }, + { + input: "a good example", + expected: "example good a", + }, + } + for _, tc := range tests { + output := reverseWords(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}