728x90
Descriptions.
Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
문자열로 괄호를 받아 짝이 유효한지에 따라 반환값을 결정하는 함수를 만들어라. 함수는 문자열이 유효하다면 true를 반환하며 그렇지 않으면 false를 반환한다.
Examples(with result).
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Constraints.
0 <= input.length <= 100
Soultion1.
function validParentheses(parens) {
let regEx = /[()]/g, // ignore characters in between
count = 0,
braket;
while(braket = regEx.exec(parens), braket !== null) {
if(braket == "(") count++;
else if(braket == ")" {
count--;
if(count < 0) return false;
}
}
return count == 0;
}
Solution2.
function validParentheses(parens) {
let count = 0;
for(let i=0; i < parens.length && count >= 0; i++) {
count += (parens[i] == "(") ? 1 : -1;
}
return (count == 0)
}
Solution3.
function validParentheses(parens) {
let n = 0;
for(let i=0; i < parens.length; i++) {
if(parens[i] == "(") n++;
if(parens[i] == ")") n--;
if(n < 0) return false;
}
return n == 0;
}
Solution4.
function vaildParentheses(parens) {
const regEx = /\(\)/g;
while(regEx.test(parens)) {
parens = parens.replace(regEx, '');
}
return !parens;
}
'1Day 1Practice' 카테고리의 다른 글
[codewars] Human Readable Time (0) | 2022.07.07 |
---|---|
[codewars] First non-repeating character (0) | 2022.06.23 |
[codewars] Stop gninnips My sdroW! (0) | 2022.06.14 |
[codewars] Isograms (0) | 2022.06.10 |
[codewar] Replace With Alphabet Position (0) | 2022.06.09 |