Algorithm or program to check for balanced parentheses in an expression using stack data structure.

For example:

[(+) * (-)] // true
{[()]} // true
{(}) // false
{*) //false

The idea to solve the problem is:

  • opening and closing parentheses should have the same number
  • last unclosed should be closed first!
const closing = [')', ']', '}'];
const opening = ['(', '[', '{'];
const matching = {
: ['(', ')'],
: ['[', ']'],
: ['{', '}']
}; const contains = ary => target => ary.includes(target);
const isOpening = contains(opening);
const isClosing = contains(closing); function balanceParentheses (str) {
let stack = [];
const isEmpty = stack => stack.length === ;
const last = stack => stack[stack.length - ]; for (let char of str) {
// if it is open char, push to the stack
if (isOpening(char)) {
stack.push(char);
}
// if it is closing char
else if (isClosing(char)) {
// if stack is not empty
if (!isEmpty(stack)) {
// check last element should be the pair of closing element
const indx = closing.indexOf(char);
const [open, close] = matching[indx];
// if it is, then pop the last element
if (last(stack) === open) {
stack.pop();
} else {
// otherwise, return false
return false;
}
} else {
return false;
}
}
} return isEmpty(stack);
} console.log(balanceParentheses('{[()(){}]}')); // true
console.log(balanceParentheses(')(')); // false
console.log(balanceParentheses('({)}')); // false
console.log(balanceParentheses('{2*3)')); // false
console.log(balanceParentheses('[(1+2)*3-(1-9)]')); //true

[Algorithm] Check for balanced parentheses using stack的更多相关文章

  1. Eclipse下Android开发错误之Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace

    升级了Android版本后,在运行应用时提示: [2013-11-27 10:37:35 - Dex Loader] Unable to execute dex: java.nio.BufferOve ...

  2. Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.

    问题提示:Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. ...

  3. [2014-03-13 08:46:42 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.

    Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. 问题提示 ...

  4. Error处理:Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack tra

    [2014-04-20 20:59:23 - MyDetectActivity] Dx  trouble writing output: already prepared [2014-04-20 20 ...

  5. 安卓常见错误Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.

    Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. 导入新的 ...

  6. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  7. 32. Longest Valid Parentheses (Stack; DP)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  8. 20. Valid Parentheses(stack)

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  9. [Leetcode] 20. Valid Parentheses(Stack)

    括号匹配问题,使用栈的特点,匹配则出栈,否则入栈,最后栈为空则全部匹配.代码如下: class Solution { public: bool isValid(string s) { stack< ...

随机推荐

  1. mongodb chunk 大小设置

    默认是64MB,取值范围是1 MB 到 1024 MB. 那改动会造成什么?下表简单总结: chunk size 调节 splitting次数(碎片数) 数据跨shard数目 数据均匀 网络传输次数 ...

  2. Canbus ID filter and mask

    Canbus ID filter and mask CANBUS is a two-wire, half-duplex, bus based LAN system that is ‘collision ...

  3. WinForm多语言版本实战项目演练

    一.课程介绍 关于如何实现“WinForm多语言版本”网上有很多实现技术方案,可以说是“琳琅满目”,"包罗万象".俗话说的好:一千个读者就有一千个哈姆雷特!如果您工作中恰好也遇到这 ...

  4. 多个RS-485设备怎么连接到一台电脑上?可以设置地址,有协议

    计算机都是RS232的,所以要给计算机串口配一个232/485转换器,然后给所有485设备设置一个地址. 计算机用查询方式,根据设备地址查询指定设备. 比如,计算机发送5个自节 01 03 04 FF ...

  5. 在TQ2440上运行perf,生成Flame Graph

    参考 http://www.cnblogs.com/helloworldtoyou/p/5585152.html  http://blog.csdn.net/mtofum/article/detail ...

  6. Delphi XE中String、ANSIString、TBytes之间的转换

    一.string转为ansistring1.直接赋值 (有警告)2.ansistring()类型强制转换.(无警告) 二.ansistring 转为string 1.直接赋值 (有警告)2.strin ...

  7. TStream实现多表查询

    TStream实现多表查询 function TynFiredac.QuerySQLS(const ASQL, ASQL2: string; AStorageFormat: string = 'bin ...

  8. java容器HashMap原理

    1.为什么需要HashMap 前面我们说了ArrayList和LinkedList,它们对容器内的对象都能实现增.删.改.查.遍历等操作, 并且对应不同的情况,我们可以选择不同的List,用以提高效率 ...

  9. 媒体文件audio 转 base64 编码 (利用 FileReader & Audio 对象)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  10. 哥谭第四季/全集Gotham迅雷下载

    <哥谭>(Gotham)第三季刚刚结束,第四季首集的集名就公布了.<Pax Penguina>这个集名在拉丁语中意味着「Pax Romana」,也就是「罗马式的和平」(Roma ...