如何基于指定参考元素数组对数学等式字符串执行拆分操作?
实现思路
- 先对参考元素数组按长度降序排序,优先匹配更长的元素,避免短元素提前匹配导致长元素被拆分错误
- 将输入的等式字符串按
=分割为左右两部分,等号单独作为拆分结果的固定项 - 分别扫描左右两边的字符串,每次从当前扫描位置尝试匹配参考数组中的元素(匹配时不区分大小写,保留原字符串的字符大小写)
- 匹配成功后将对应子串加入结果数组,移动扫描指针到匹配子串的末尾,重复直到整个字符串扫描完成
代码实现(JavaScript)
function splitEquation(equationStr, refs) { // 参考数组按长度降序排序,长元素优先匹配 const sortedRefs = [...refs].sort((a, b) => b.length - a.length); // 拆分等号左右部分 const [leftPart, rightPart] = equationStr.split('='); // 拆分单个字符串的工具函数 const splitPart = (str) => { const result = []; let index = 0; const len = str.length; while (index < len) { let matched = false; for (const ref of sortedRefs) { const refLen = ref.length; if (index + refLen > len) continue; // 不区分大小写匹配,不需要可删除.toLowerCase() if (str.slice(index, index + refLen).toLowerCase() === ref.toLowerCase()) { result.push(str.slice(index, index + refLen)); index += refLen; matched = true; break; } } if (!matched) { // 未匹配到参考元素时默认取单个字符,可按需调整异常逻辑 result.push(str[index]); index += 1; } } return result; } // 拼接左右部分和等号 return [...splitPart(leftPart), '=', ...splitPart(rightPart)]; }
测试验证
所有示例运行结果符合预期:
console.log(splitEquation('Wt=mg', ['Wt', 'm', 'g'])); // 输出: ['Wt', '=', 'm', 'g'] console.log(splitEquation('maa=tna', ['ma', 'a', 't', 'n'])); // 输出: ['ma', 'a', '=', 't', 'n', 'a'] console.log(splitEquation('Fnet=ma', ['Fnet', 'm', 'a'])); // 输出: ['Fnet', '=', 'm', 'a'] console.log(splitEquation('Wt=mgt', ['wt', 'm', 'g', 't'])); // 输出: ['Wt', '=', 'm', 'g', 't']
内容的提问来源于stack exchange,提问作者Dark Prism
相关产品推荐
相关产品推荐

