我考虑用正则去做,正则写半天没写出来,求高人解救测试规则如下:
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
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
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('') }
只用正则是做不到的
用正则和Map可以实现,累加变量的系数存到Map里,最后按变量名排序,手机不好打字
只用正则是做不到的
用正则和Map可以实现,累加变量的系数存到Map里,最后按变量名排序,手机不好打字