Created
February 2, 2022 14:31
-
-
Save hinupurthakur/dec3ba622da82be73a20e8b8276df0fd to your computer and use it in GitHub Desktop.
To check if brackets are balanced in a string. Balanced brackets look like: “(())()”, “((()))”, “()”… Unbalanced brackets: “(((”, “())”, “(("
This file contains hidden or 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" | |
// function to check if brackets are balanced | |
func isBalanced(expr string) bool { | |
brackets := map[rune]rune{ | |
'(': ')', | |
'[': ']', | |
'{': '}', | |
} | |
stack := make([]rune, 0, len(expr)) | |
isBalanced := true | |
for _, c := range expr { | |
if _, ok := brackets[c]; ok == true { | |
stack = append(stack, c) | |
} else if len(stack) == 0 { | |
isBalanced = false | |
break | |
} else if brackets[stack[len(stack)-1]] != c { | |
isBalanced = false | |
break | |
} else { | |
stack = stack[:len(stack)-1] | |
} | |
} | |
if len(stack) != 0 { | |
isBalanced = false | |
} | |
return isBalanced | |
} | |
// Driver code | |
func main() { | |
// Function call | |
fmt.Println(isBalanced("")) // true (conditional ask the interviwer about this condition before start coding) | |
fmt.Println(isBalanced("expr")) // false | |
fmt.Println(isBalanced("[(}]")) // false | |
fmt.Println(isBalanced("()")) // true | |
fmt.Println(isBalanced("[{()}]")) // true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment