Created
June 20, 2024 12:53
-
-
Save joubertredrat/6da0b225b889a46e2bdca5411e4fad25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Write a function that can discern whether a given string is a valid chunk. There are one or more chunks in each string, and chunks contain zero or more other chunks. Adjacent chunks are not separated by any delimiter; if one chunk stops, the next chunk (if any) can immediately start. Every chunk must open and close with one of four legal pairs of matching characters: | |
If a chunk opens with (, it must close with ). | |
If a chunk opens with [, it must close with ]. | |
If a chunk opens with {, it must close with }. | |
If a chunk opens with <, it must close with >. | |
Valid chunks: | |
() | |
([]) | |
<>{}[] | |
{()()()} | |
[<>({}){}[([])<>]] | |
(((((((((()))))))))) | |
Invalid chunks: | |
> | |
[ | |
(] | |
{()()()> | |
<([]){()}[{}]) | |
{([(<{}[<>[]}>{[]{[(<()> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func isValidChunk(s string) bool { | |
stack := make([]rune, 0) | |
for _, ch := range s { | |
switch ch { | |
case '(', '[', '{', '<': | |
stack = append(stack, ch) | |
case ')': | |
if len(stack) == 0 || stack[len(stack)-1] != '(' { | |
return false | |
} | |
stack = stack[:len(stack)-1] | |
case ']': | |
if len(stack) == 0 || stack[len(stack)-1] != '[' { | |
return false | |
} | |
stack = stack[:len(stack)-1] | |
case '}': | |
if len(stack) == 0 || stack[len(stack)-1] != '{' { | |
return false | |
} | |
stack = stack[:len(stack)-1] | |
case '>': | |
if len(stack) == 0 || stack[len(stack)-1] != '<' { | |
return false | |
} | |
stack = stack[:len(stack)-1] | |
default: | |
// Ignore other characters | |
} | |
} | |
return len(stack) == 0 | |
} | |
func main() { | |
validChunks := []string{ | |
"()", | |
"([])", | |
"<>{}[]", | |
"{()()()}", | |
"[<>({}){}[([])<>]]", | |
"(((((((((())))))))))", | |
} | |
invalidChunks := []string{ | |
">", | |
"[", | |
"(]", | |
"{()()()>", | |
"<([]){()}[{}])", | |
"{([(<{}[<>[]}>{[]{[(<()>", | |
} | |
fmt.Println("Valid Chunks:") | |
for _, chunk := range validChunks { | |
fmt.Printf("%s: %t\n", chunk, isValidChunk(chunk)) | |
} | |
fmt.Println("\nInvalid Chunks:") | |
for _, chunk := range invalidChunks { | |
fmt.Printf("%s: %t\n", chunk, isValidChunk(chunk)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment