Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(LeetCode #20): add Valid input Parentheses pair solution #26

Merged
merged 1 commit into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions LeetCode/problem020_ValidParentheses.go
Original file line number Diff line number Diff line change
@@ -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
}
33 changes: 33 additions & 0 deletions LeetCode/problem020_ValidParentheses_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading