Skip to content

Instantly share code, notes, and snippets.

@skylying
Created October 28, 2015 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skylying/d34c366898ba295a2c3f to your computer and use it in GitHub Desktop.
Save skylying/d34c366898ba295a2c3f to your computer and use it in GitHub Desktop.
Q3
var rule = /\(([^)(]+)\)/;
var map = {
'*': 1,
'/': 1,
'+': 0,
'-': 0
}
function getHighLow(str) {
var l = str.length;
var result = [];
for (var i = 0; i < l; i++) {
if (map[str[i]] !== undefined) {
result.push(map[str[i]]);
}
}
return result.reverse();
}
function detachQuote(eq, compare) {
var times = compare.length - 1;
var str = eq;
var matchMap = {
'[': '(',
']': ')'
};
for (var j = 0; j < times; j++) {
var noParen = rule.exec(str)[1];
// Parentheses cannot be removed
if (compare[j+1] > compare[j]) {
var tmp = str.replace(rule, '[' + noParen + ']');
} else { // can be removed
var tmp = str.replace(rule, noParen);
}
str = tmp;
}
var finalAnswer = str.replace(/\[|\]/g, function(match) {
return matchMap[match];
})
return finalAnswer;
}
function magic(str) {
var compareRule = getHighLow(str);
return detachQuote(str, compareRule);
}
var answer = magic("2*(2+(3*(4+5)))");
// will return 2*(2+3*(4+5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment