Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <title>JS Bin</title>
- </head>
- <body>
- <script id="jsbin-javascript">
- 'use strict';
- var getBalancedLength = function getBalancedLength(str) {
- if (typeof str !== 'string') {
- console.error('Invalid type string.');
- }
- var token_queue = [];
- var res = [];
- var count = 0;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
- try {
- for (var _iterator = str[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- char = _step.value;
- if (/\(/.test(char)) token_queue.push(1);else if (/\)/.test(char)) {
- if (token_queue.length) {
- token_queue.shift();
- count += 2;
- } else {
- res.push(count);
- count = 0;
- }
- } else {
- console.error('Invalid type string.');
- break;
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator['return']) {
- _iterator['return']();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
- res.push(count);
- return Math.max.apply(Math, res);
- };
- console.clear();
- console.log(getBalancedLength(''));
- console.log(getBalancedLength('(a)'));
- console.log(getBalancedLength(')('));
- console.log(getBalancedLength('()'));
- console.log(getBalancedLength('))(()()))'));
- console.log(getBalancedLength('()())()((()))'));
- </script>
- <script id="jsbin-source-javascript" type="text/javascript">const getBalancedLength = (str) => {
- if(typeof str !== 'string') {
- console.error('Invalid type string.');
- }
- const token_queue = [];
- const res = [];
- let count = 0;
- for(char of str) {
- if(/\(/.test(char))
- token_queue.push(1);
- else if(/\)/.test(char)) {
- if(token_queue.length) {
- token_queue.shift();
- count += 2;
- } else {
- res.push(count);
- count = 0;
- }
- } else {
- console.error('Invalid type string.');
- break;
- }
- }
- res.push(count);
- return Math.max(...res);
- }
- console.clear();
- console.log(getBalancedLength(''));
- console.log(getBalancedLength('(a)'));
- console.log(getBalancedLength(')('));
- console.log(getBalancedLength('()'));
- console.log(getBalancedLength('))(()()))'));
- console.log(getBalancedLength('()())()((()))'));
- </script></body>
- </html>
Add Comment
Please, Sign In to add comment