方向縮減挑戰要求您從方向數組中找到最短路線。
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中文網其他相關文章!