From b6fc7729ff174dbce61088c960dc44dab4c97b26 Mon Sep 17 00:00:00 2001 From: Angelica Hjelm Gardner Date: Sun, 17 Nov 2024 23:06:01 +0100 Subject: [PATCH] feat(LeetCode #20): add Valid input Parentheses pair solution --- LeetCode/problem020_ValidParentheses.go | 36 ++++++++++++++++++++ LeetCode/problem020_ValidParentheses_test.go | 33 ++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 LeetCode/problem020_ValidParentheses.go create mode 100644 LeetCode/problem020_ValidParentheses_test.go diff --git a/LeetCode/problem020_ValidParentheses.go b/LeetCode/problem020_ValidParentheses.go new file mode 100644 index 0000000..e2ebe15 --- /dev/null +++ b/LeetCode/problem020_ValidParentheses.go @@ -0,0 +1,36 @@ +/* +Problem 20. Valid Parentheses +*/ + +package leetcode + +// Time complexity: O(n) +// Space complexity: O(n) +func isValid(s string) bool { + stack := []rune{} + + bracketMap := map[rune]rune{ + ')': '(', + '}': '{', + ']': '[', + } + + for _, char := range s { + if char == '(' || char == '{' || char == '[' { + stack = append(stack, char) + } else { + if len(stack) == 0 { + return false + } + + top := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + if top != bracketMap[char] { + return false + } + } + } + + return len(stack) == 0 +} diff --git a/LeetCode/problem020_ValidParentheses_test.go b/LeetCode/problem020_ValidParentheses_test.go new file mode 100644 index 0000000..e63951d --- /dev/null +++ b/LeetCode/problem020_ValidParentheses_test.go @@ -0,0 +1,33 @@ +package leetcode + +import ( + "testing" +) + +func TestIsValid(t *testing.T) { + var tests = []struct { + name string + inputString string + expected bool + }{ + {"Case 1", "()", true}, + {"Case 2", "()[]{}", true}, + {"Case 3", "(]", false}, + {"Case 4", "{[]}", true}, + {"Correct and incorrect example", "{[}", false}, + {"Empty string", "", true}, + {"Only opening parentheses", "(", false}, + {"Only closing parentheses", ")", false}, + {"Longer correct example", "({[]})[]{}", true}, + {"Longer incorrect example", "({[]})[]{}{", false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := isValid(tt.inputString) + if result != tt.expected { + t.Errorf("isValid(%q) = %v; expected %v", tt.inputString, result, tt.expected) + } + }) + } +}