reverse words 557

main
Jason Staten 2 years ago
parent fa498ba5f1
commit 943c558f8f

@ -0,0 +1,9 @@
package main
import (
"log"
)
func main() {
log.Printf("Hi")
}

@ -0,0 +1,27 @@
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
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.

@ -0,0 +1,19 @@
package reversewords
import "strings"
func reverse(s string) string {
result := make([]rune, len(s))
for i, v := range s {
result[len(result)-i-1] = v
}
return string(result)
}
func ReverseWords(s string) string {
words := strings.Fields(s)
for i, v := range words {
words[i] = reverse(v)
}
return strings.Join(words, " ")
}

@ -0,0 +1,29 @@
package reversewords_test
import (
"fmt"
"testing"
"git.jxs.me/leetgo/reversewords"
)
func TestExamples(t *testing.T) {
cases := map[string]string{
"": "",
"foo": "oof",
"Hello World": "olleH dlroW",
"Let's take LeetCode contest": "s'teL ekat edoCteeL tsetnoc",
}
for source, expected := range cases {
t.Run(fmt.Sprintf("Check %q", source), func(t *testing.T) {
result := reversewords.ReverseWords(source)
if expected != result {
t.Errorf("%q != %q", expected, result)
}
})
}
}
Loading…
Cancel
Save