-
[Codewars] Valid BracesAlgorithm 2020. 11. 16. 23:53
www.codewars.com/kata/5277c8a221e209d3f6000b56/train/javascript
더보기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.
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
수도코드
괄호 개수를 체크 여는 괄호가 나오면 카운트를 1씩 증가 닫는 괄호가 있는데 카운트가 0이면 false 닫는 괄호가 나오면 카운트를 1씩 감소 조건문 다 통과하고 카운트가 0이면 열고 닫는 괄호가 짝에 맞게 있다는 뜻이므로 true
풀이
function validBraces(braces){ let parenthesis = 0 let brace = 0 let bracket = 0 for (let i = 0; i < braces.length; i++) { if(braces[i] === "(") { parenthesis++ } if(braces[i] === "{") { brace++ } if(braces[i] === "[") { bracket++ } if(braces[i] === ")") { if(parenthesis === 0) { return false } else { parenthesis-- } } if(braces[i] === "}") { if(brace === 0) { return false } else { brace-- } } if(braces[i] === "]") { if(bracket === 0) { return false } else { bracket-- } } } if(parenthesis === 0 && brace === 0 && bracket === 0) { return true } else { return false } }
'Algorithm' 카테고리의 다른 글
[프로그래머스] 소수 찾기 (0) 2021.01.18 [프로그래머스] 약수의 합 (0) 2021.01.18 [Codewars] Format a string of names like 'Bart, Lisa & Maggie' (0) 2020.11.08 [Codewars] Are they the "same"? (0) 2020.11.08 [Codewars] Who likes it? (0) 2020.10.28