Maison > Questions et réponses > le corps du texte
我考虑用正则去做,正则写半天没写出来,求高人解救测试规则如下:
simplify("3x+y-x+2y+5xy-y-xy") => 2x+2y+4xy simplify("2xy-yx") =>xy simplify("xzy+zby") =>byz+xyz simplify("xzy+zby") =>byz+xyz simplify("y-x")=>-x+y
欧阳克2016-11-10 16:18:53
function simplify (expression) { let variables = {}, reg = /([\+\-]?)(\d*)([a-zA-Z]+)/g, matched while (matched = reg.exec(expression)) { let sign = matched[1] || '+' let num = matched[2] || '1' let variable = [].slice.call(matched[3]).sort().join('') variables[variable] = (variables[variable] || 0) + +(sign + num) } let result = [] for (let variable in variables) { let num = variables[variable] result.push([num > 0 ? '+': '', num, variable].join('')) } return result.join('') }
只用正则是做不到的