592. Addition and subtraction of fractions

Leetcode-cn.com/problems/fr…

  • Regular expression forward lookingexp1(? =exp2)Find exp1 in front of exp2.exp1(? ! exp2): find exp1 not followed by exp2.
  • Regular expressions are backward(? <=exp2)exp1Select exp1 from exp2.(? <! exp2)exp1: find exp1 that does not start with exp2.
/** * @param {string} expression * @return {string} */ var fractionAddition = function(expression) { const reg = / [\ \ +]? [0-910]+\/[0-910]+/g const matchs = expression.match(reg) const numeratorReg = /\*{1}(? =\/)/g const denominatorReg = /(? <=\/)\*/ const stack = [] let res = matchs[0] for(let i=0; i<matchs.length; i++){ while(stack.length){ const curr = stack.pop() res = calcRes(curr,matchs[i]) } stack.push(res) } function calcRes(num1,num2){ let [numerator1,denominator1] = num1.split("\/") let [numerator2,denominator2] = num2.split("\/") let denominatorRes = Number(denominator1) * Number(denominator2) let numeratorRes = Number(numerator1) * Number(denominator2) + Number(numerator2) * Number(denominator1) let i =2 while(i<= Math.abs(numeratorRes)){ if(numeratorRes % i ===0 && denominatorRes % i ===0){ numeratorRes = numeratorRes/i denominatorRes = denominatorRes/i }else{ i++ } } if(numeratorRes ==0){ denominatorRes = 1 } return `${numeratorRes}/${denominatorRes}` } return res };Copy the code

640. Solve the equation

Leetcode-cn.com/problems/so…

/** * @param {string} equation * @return {string} */ var solveEquation = function (equation) { equation = "+" + equation  let euqaIndex = equation.indexOf("=") const reverseReg = /[\-\+]/g let left = equation.slice(0, euqaIndex) let right = ("+" + equation.slice(euqaIndex + 1)).replace(reverseReg, (match, p1, p2) => { if (match === "+") return "-" if (match === "-") return "+" }) let transEquation = left + right let patten1 = /[\+\-]{1}[0-9]*x/g let filteredTransEquation = transEquation.replace(patten1,"") let sumPatten = /\+[0-9]+/g let diffPatten = /\-[0-9]+/g const sumMatch = filteredTransEquation.match(sumPatten) || [] const diffMatch = filteredTransEquation.match(diffPatten) || [] let sum = 0 let sum2 = 0 sumMatch.concat(diffMatch).forEach(num => { sum =  sum + Number(num) }) const mutiplyMatch = transEquation.match(patten1) if (mutiplyMatch) { for (let i = 0; i < mutiplyMatch.length; i++) { if (mutiplyMatch[i] === "+x") { sum2++ continue } if (mutiplyMatch[i] === "-x") { sum2-- continue } sum2 = Number(mutiplyMatch[i].match(sumPatten)) + Number(mutiplyMatch[i].match(diffPatten)) + sum2 } } if (sum2 === 0) { if (sum === 0) { return "Infinite solutions" } else { return "No solution" } } return "x=" + (-sum / sum2) };Copy the code