Skip to content

[bus710] Week 06 #887

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

Merged
merged 2 commits into from
Jan 17, 2025
Merged
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
55 changes: 55 additions & 0 deletions valid-parentheses/bus710.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package hello

import (
"strings"
)

const (
openChar = "({["
closeChar = ")]}"
)

func isValid(s string) bool {
ss := strings.Split(s, "")
stack := []string{}

// If the very first one is not an opening character,
// no need to check followings
if !strings.Contains(openChar, ss[0]) || !strings.Contains(closeChar, ss[len(ss)-1]) {
return false
}

// If the length is not even, there is an incomplete pair
if len(ss)%2 == 1 {
return false
}

// Loop over the slice to check
// - If the current one is an opening one, then push into the stack
// - If the current one is a closing one, then pop and compare with the previous one from the stack
for _, c := range ss {
if strings.Contains(openChar, c) {
stack = append(stack, c)
} else if strings.Contains(closeChar, c) {
if len(stack) == 0 {
return false
}
prev := stack[len(stack)-1]

switch {
case prev == "(" && c == ")":
fallthrough
case prev == "[" && c == "]":
fallthrough
case prev == "{" && c == "}":
stack = stack[:len(stack)-1]
default:
stack = append(stack, c)
}
} else {
// In case of non-parenthesis character found
return false
}
}
return len(stack) == 0
}
Loading