물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Valid Braces

BEstyle 2022. 10. 6. 13:11

DESCRIPTION:

Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.

This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {}. Thanks to @arnedag for the idea!

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

Examples

"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False

def valid_braces(string):
    while "()" in string or "[]" in string or "{}" in string:
        if "()" in string:
            string=string.replace("()","")
        if "[]" in string:
            string=string.replace("[]","")
        if "{}" in string:
            string=string.replace("{}","")
    return string==""

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Detect Pangram  (0) 2022.10.07
Bouncing Balls  (0) 2022.10.07
Valid Parentheses  (0) 2022.10.06
RGB to Hex Conversion  (0) 2022.10.06
Human Readable Time  (0) 2022.10.05