From 8546ffc099f7145059a76875abe7ff09a3e9e950 Mon Sep 17 00:00:00 2001 From: openset Date: Fri, 31 May 2019 11:11:48 +0800 Subject: [PATCH] Add: Remove All Adjacent Duplicates In String --- ...emove_all_adjacent_duplicates_in_string.go | 14 ++++++++++ ..._all_adjacent_duplicates_in_string_test.go | 27 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string.go create mode 100644 problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string_test.go diff --git a/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string.go b/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string.go new file mode 100644 index 000000000..e1de6d0e8 --- /dev/null +++ b/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string.go @@ -0,0 +1,14 @@ +package remove_all_adjacent_duplicates_in_string + +func removeDuplicates(S string) string { + ans := make([]byte, 0, len(S)) + for i := 0; i < len(S); i++ { + n := len(ans) + if n >= 1 && ans[n-1] == S[i] { + ans = ans[:n-1] + } else { + ans = append(ans, S[i]) + } + } + return string(ans) +} diff --git a/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string_test.go b/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string_test.go new file mode 100644 index 000000000..c0bfecd7f --- /dev/null +++ b/problems/remove-all-adjacent-duplicates-in-string/remove_all_adjacent_duplicates_in_string_test.go @@ -0,0 +1,27 @@ +package remove_all_adjacent_duplicates_in_string + +import "testing" + +type caseType struct { + input string + expected string +} + +func TestRemoveDuplicates(t *testing.T) { + tests := [...]caseType{ + { + input: "abbaca", + expected: "ca", + }, + { + input: "aaabaca", + expected: "abaca", + }, + } + for _, tc := range tests { + output := removeDuplicates(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}