From 697f63dd8f3dad4bfe46debfb628e1de33bb41f2 Mon Sep 17 00:00:00 2001 From: Shuo Date: Thu, 2 Jul 2020 17:51:04 +0800 Subject: [PATCH] A: Reformat The String --- .../reformat_the_string.go | 26 ++++++++ .../reformat_the_string_test.go | 63 +++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 problems/reformat-the-string/reformat_the_string.go create mode 100644 problems/reformat-the-string/reformat_the_string_test.go diff --git a/problems/reformat-the-string/reformat_the_string.go b/problems/reformat-the-string/reformat_the_string.go new file mode 100644 index 000000000..840d70c1d --- /dev/null +++ b/problems/reformat-the-string/reformat_the_string.go @@ -0,0 +1,26 @@ +package problem1417 + +func reformat(s string) string { + i, j, l := 0, 1, len(s) + str := make([]byte, l+1) + for _, c := range s { + if '0' <= c && c <= '9' { + if i > l { + return "" + } + str[i], i = byte(c), i+2 + } else if j > l { + return "" + } else { + str[j], j = byte(c), j+2 + } + } + if i == l || j == l { + return string(str[:l]) + } + if i == l-1 { + str[i] = str[0] + return string(str[1 : l+1]) + } + return "" +} diff --git a/problems/reformat-the-string/reformat_the_string_test.go b/problems/reformat-the-string/reformat_the_string_test.go new file mode 100644 index 000000000..691a6f023 --- /dev/null +++ b/problems/reformat-the-string/reformat_the_string_test.go @@ -0,0 +1,63 @@ +package problem1417 + +import "testing" + +type testType struct { + in string + want string +} + +func TestReformat(t *testing.T) { + tests := [...]testType{ + { + in: "a0b1c2", + want: "0a1b2c", + }, + { + in: "leetcode", + want: "", + }, + { + in: "1229857369", + want: "", + }, + { + in: "covid2019", + want: "c0o1v9i2d", + }, + { + in: "ab123", + want: "1a2b3", + }, + { + in: "ec", + want: "", + }, + { + in: "abcd12345", + want: "1a2b3c4d5", + }, + { + in: "12345abcd", + want: "1a2b3c4d5", + }, + { + in: "77", + want: "", + }, + { + in: "1", + want: "1", + }, + { + in: "a", + want: "a", + }, + } + for _, tt := range tests { + got := reformat(tt.in) + if got != tt.want { + t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want) + } + } +}