方向缩减挑战要求您从方向数组中找到最短路线。
Input -> Output ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] -> ["WEST"] /* Because moving "NORTH" and "SOUTH", or "EAST" and "WEST", is unnecessary. */ /* Case: omit the first "NORTH"-"SOUTH" pair ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] -> ["SOUTH", "EAST", "WEST", "NORTH", "WEST"] Case: omit the "EAST"-"WEST" pair -> ["SOUTH", "NORTH", "WEST"] Case: omit the "NORTH"-"SOUTH" pair -> ["WEST"] */ // this case cannot be reduced: ["NORTH", "WEST", "SOUTH", "EAST"] -> ["NORTH", "WEST", "SOUTH", "EAST"]
function dirReduc(plan) { var opposite = { 'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'}; return plan.reduce(function(dirs, dir){ if (dirs[dirs.length - 1] === opposite[dir]) dirs.pop(); // Remove last direction if it's the opposite else dirs.push(dir); // Otherwise, add current direction to the stack return dirs; }, []); }
这是使用reduce实现的LIFO(后进先出)方法。
function dirReduce(arr) { let str = arr.join(''), pattern = /NORTHSOUTH|EASTWEST|SOUTHNORTH|WESTEAST/; while (pattern.test(str)) str = str.replace(pattern,''); // Remove pairs while they exist return str.match(/(NORTH|SOUTH|EAST|WEST)/g)||[]; }
替代版本:
function dirReduc(arr) { const pattern = /NORTHSOUTH|EASTWEST|SOUTHNORTH|WESTEAST/; let str = arr.join(''); while (pattern.test(str)) { str = str.replace(pattern, ''); // Remove pairs while they exist } const result = str.match(/(NORTH|SOUTH|EAST|WEST)/g); return result || []; }
我认为该解决方案的最低情况如下:
1. ["SOUTH", "EAST", "WEST", "NORTH"] -> [] 2. ["NORTH", "WEST", "SOUTH", "EAST"] -> ["NORTH", "WEST", "SOUTH", "EAST"]
我更喜欢解决方案2,因为它简洁并且巧妙地使用了正则表达式。最初,我无法想象用正则表达式来解决它,但是使用 join、match、while、replace 和 test 方法来消除对是令人印象深刻的。
如果您对这些解决方案感到好奇或想探索更多挑战,请访问此处。
欢迎在下方留言!
感谢您的阅读?
以上是TIL:后进先出的解决方案和正则表达式技术【CodeWars】的详细内容。更多信息请关注PHP中文网其他相关文章!