ValidBraces

samuel Jo·2022년 11월 11일
0

codewars

목록 보기
2/46

문제

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

백준의 9012문제와 동일하다.
"(" 이렇게 여는괄호가 나타나면 ")"닫히는 괄호가 나오면 true
"(" 이렇게 여는괄호가 나타나면 ")"닫히는 괄호가 나오지 않으면 false

function validBraces(braces) {
  var matches = { "(": ")", "{": "}", "[": "]" };
  var stack = [];
  var currentChar;

  for (var i = 0; i < braces.length; i++) {
    currentChar = braces[i];

    if (matches[currentChar]) {
      stack.push(currentChar);
    } else {
      if (currentChar !== matches[stack.pop()]) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

처음 작성한 코드는
여는괄호가 나오면 변수안에 +1 , 닫히는괄호가 나오면 -1을 만들어서 0 이면 true를
아니면 false를 반환하게 했는데 새로 짜봤다.

요즘 codewar를 이용해서 하루 한문제씩 풀려고 노력중이다.

profile
step by step

0개의 댓글