From 2cbe93b3a9d48457c5c90addef38562b96f43fda Mon Sep 17 00:00:00 2001 From: VicRen Date: Fri, 20 Nov 2020 09:50:04 +0800 Subject: [PATCH] 20201120 --- 20201120/main.go | 38 +++++++++++++++ 20201120/main_test.go | 104 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 20201120/main.go create mode 100644 20201120/main_test.go diff --git a/20201120/main.go b/20201120/main.go new file mode 100644 index 0000000..bc5a6ca --- /dev/null +++ b/20201120/main.go @@ -0,0 +1,38 @@ +package main + +func main() { + +} + +func turnOver(s string) string { + var letters []int32 + m := make(map[int]int32) + for i, c := range s { + if isLetter(c) { + letters = append(letters, c) + } else { + m[i] = c + } + } + var ret []int32 + for i := len(letters) - 1; i >= 0; i-- { + ret = append(ret, letters[i]) + } + for k, v := range m { + ret = insert(ret, k, v) + } + return string(ret) +} + +func isLetter(s int32) bool { + return (s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z') +} + +func insert(a []int32, index int, value int32) []int32 { + if len(a) == index { // nil or empty slice or after last element + return append(a, value) + } + a = append(a[:index+1], a[index:]...) // index < len(a) + a[index] = value + return a +} diff --git a/20201120/main_test.go b/20201120/main_test.go new file mode 100644 index 0000000..2bd6065 --- /dev/null +++ b/20201120/main_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "reflect" + "testing" +) + +func Test_turnOver(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want string + }{ + { + "example_1", + args{"ab-cd"}, + "dc-ba", + }, + { + "example_2", + args{"a-bC-dEf-ghIj"}, + "j-Ih-gfE-dCba", + }, + { + "example_3", + args{"Test1ng-Leet=code-Q!"}, + "Qedo1ct-eeLg=ntse-T!", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := turnOver(tt.args.s); got != tt.want { + t.Errorf("turnOver() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_isLetter(t *testing.T) { + type args struct { + s int32 + } + tests := []struct { + name string + args args + want bool + }{ + { + "a", + args{'a'}, + true, + }, + { + "U", + args{'U'}, + true, + }, + { + "-", + args{'-'}, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isLetter(tt.args.s); got != tt.want { + t.Errorf("isLetter() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_insert(t *testing.T) { + type args struct { + a []int32 + index int + value int32 + } + tests := []struct { + name string + args args + want []int32 + }{ + { + "test_1", + args{ + []int32{1, 2, 3}, + 1, + 32, + }, + []int32{1, 32, 2, 3}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := insert(tt.args.a, tt.args.index, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("insert() = %v, want %v", got, tt.want) + } + }) + } +}