Valid Braces ( 4 kyu )

문제

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

괄호가 순서쌍이 맞게 이루어졌으면 true, 아니면 false 리턴

풀이

function validBraces(braces){
  while ( braces.indexOf("()") !== -1 || braces.indexOf("{}") !== -1 || braces.indexOf("[]") !== -1 ) {
    if ( braces.indexOf("()") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("()")).concat(braces.slice(braces.indexOf("()")+2, braces.length))
    } else if ( braces.indexOf("{}") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("{}")).concat(braces.slice(braces.indexOf("{}")+2, braces.length))
    } else if ( braces.indexOf("[]") !== -1 ) {
      braces = braces.slice(0, braces.indexOf("[]")).concat(braces.slice(braces.indexOf("[]")+2, braces.length))
    } 
  }
  return braces.length === 0 ? true : false;
}

while에 indexOf로 괄호쌍을 지워가면서 문자열이 전부 삭제되면 true 리턴, 아니라면 false 리턴

다른 사람의 풀이

function validBraces(braces){
 while(/\(\)|\[\]|\{\}/g.test(braces)){braces = braces.replace(/\(\)|\[\]|\{\}/g,"")}
 return !braces.length;
}

뭔진모르지만 고수느낌


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Palindrome chain length ( 5 kyu )  (0) 2017.11.29
Tribonacci Sequence ( 6 kyu )  (0) 2017.11.28
Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Counting Duplicates ( 6 kyu )  (0) 2017.11.26

+ Recent posts