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: Valid Parentheses solution added with unit and benchmark test case #216

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/nikzayn/leetcode

go 1.21.1
35 changes: 35 additions & 0 deletions LeetCode/2116. Check if a Parentheses String Can Be Valid/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import "fmt"

func isValidParentheses(s string) bool {
stack := []rune{}
parenthesesMap := map[rune]rune{')': '(', '}': '{', ']': '['}

for _, char := range s {
if char == '(' || char == '{' || char == '[' {
stack = append(stack, char)
} else if char == ')' || char == '}' || char == ']' {
if len(stack) == 0 {
return false
}
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if parenthesesMap[char] != top {
return false
}
}
}

return len(stack) == 0
}

func main() {
inputStr := "{[()]}"

if isValidParentheses(inputStr) {
fmt.Printf("The parentheses string '%s' is valid.\n", inputStr)
} else {
fmt.Printf("The parentheses string '%s' is not valid.\n", inputStr)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import "testing"

func TestIsValidParentheses(t *testing.T) {
testCases := []struct {
input string
expected bool
}{
{"{[()]}", true}, // Valid parentheses string
{"{[(])}", false}, // Invalid parentheses string
{"", true}, // An empty string is considered valid
{"()", true}, // Valid parentheses string
{"(())", true}, // Valid parentheses string
{"[({})]", true}, // Valid parentheses string
{"[({})]}", false}, // Invalid parentheses string
{"{[()()]}", true}, // Valid parentheses string
{"{[()()]", false}, // Invalid parentheses string
{"{{[()]}", false}, // Invalid parentheses string
{"[({})]", true}, // Valid parentheses string
}

for _, testCase := range testCases {
t.Run(testCase.input, func(t *testing.T) {
result := isValidParentheses(testCase.input)
if result != testCase.expected {
t.Errorf("Input: %s, Expected: %v, Got: %v", testCase.input, testCase.expected, result)
}
})
}
}

func BenchmarkIsValidParentheses(b *testing.B) {
inputStr := "{[()]}"
for i := 0; i < b.N; i++ {
isValidParentheses(inputStr)
}
}