Валидация скобок
Подскажите, как улучшить/упростить?
function isValid(str) {
const pairs = {
'(': ')',
'{': '}',
'[': ']'
}
const stack = [];
for (let s of str) {
if (s == '(' || s == '{' || s == '[') {
stack.push(pairs[s]);
}
if (s == ')' || s == '}' || s == ']') {
if (s != stack[stack.length - 1]) {
return false;
} else {
stack.pop(stack[stack.length - 1]);
}
}
}
return true;
}
console.log(isValid('(hello{world} and [me])')); // true
console.log(isValid('(hello{world)} and [me])')); // false
console.log(isValid(')')); // false
|
function isValid(str) {
const pairs = {
'(': ')',
'{': '}',
'[': ']'
};
const closes = Object.values(pairs);
const stack = [];
for (let s of str) {
if (pairs[s]) {
stack.push(pairs[s]);
} else if (closes.includes(s) && s !== stack.pop()) {
return false;
}
}
return !stack.length;
}
|
Alexandroppolus,
грамотно. Благодарю. |
| Часовой пояс GMT +3, время: 04:37. |