Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created March 30, 2020 00:18
Show Gist options
  • Save RP-3/90742a555ac0813e391c3894339940f5 to your computer and use it in GitHub Desktop.
Save RP-3/90742a555ac0813e391c3894339940f5 to your computer and use it in GitHub Desktop.
/**
* @param {string} s
* @return {number}
*/
// Straight-up stack. O(n) time and space since every character
// is inspected at worst a fixed number of times.
var calculate = function(s) {
// question constraint: ignore unary negatives
const parsed = parse(s); // remove spaces, convert strings to ints
const stack = [];
// evaluate multiplication and division
for(let i=0; i<parsed.length; i++){
const token = parsed[i];
if(token === '/' || token === '*'){
const [left, right] = [stack.pop(), parsed[i+1];
stack.push(token === '*' ? (left * right) : Math.floor(left/right));
i++;
}else stack.push(token);
}
// evaluate addition and subtraction
let result = stack[0];
let op = null;
for(let i=1; i<stack.length; i++){
const token = stack[i];
if(token === '+' || token === '-') op = token;
else result = op === '+' ? result + token : result - token;
}
return result;
function parse(str){
let cleanStr = str.replace(/\s/g, ''); // remove all spaces
let currentNum = [];
const result = [];
for(let i=0; i<cleanStr.length; i++){
const token = cleanStr[i];
if(token.match(/[0-9]/)) currentNum.push(token);
else{
if(currentNum.length){
const numStr = currentNum.join('');
result.push(parseInt(numStr, 10));
currentNum = [];
}
result.push(token);
}
}
if(!currentNum.length) return result;
const numStr = currentNum.join('');
result.push(parseInt(numStr, 10));
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment