簡體   English   中英

擴展使用Javascript array.reduce輔助方法

[英]Expanding use of Javascript array.reduce helper method

背景

我正在學習關於Udemy的課程,該課程涵蓋了所有ES6功能。 在其中一個課程中,講師談到使用reduce輔助方法來解決流行的平衡括號面試問題。

沒有reduce方法,我可以解決這個問題。 雖然使用reduce方法,但它確實可以用更少的代碼完成工作。 我之前被要求在一次采訪中找到括號的深度,並且想知道是否可以使用reduce在同一方法中完成所有這些操作。

我不知道為什么這個問題的補充讓我很困惑,但我想學習。

問題

我一直試圖弄清楚它有一段時間,可能是我缺乏理解如何減少工作。

如果括號或均勻打開和關閉,則使用reduce返回false的true。

function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));

如何使用reduce helper方法返回括號的最大深度。

您可以在減少時保持當前深度和最大深度。

 function maxDepth(string) { return string.split("").reduce(({current, max}, char) => { // Handle if parens open and close out of order if (current < 0) return {current, max} // Add 1 for each open in order if (char === "(") return { current: current + 1, max: Math.max(max, current + 1)} // subtract 1 for each close in order if (char === ")") return { current: current - 1, max} return {current, max} }, {current: 0, max: 0}).max; } console.log(maxDepth("(((()))(((())))()(((((()))))))")); 

這是一個緊湊版本,當括號不平衡時返回NaN 它使用功能樣式的嵌套函數:

 function maxDepth(string) { return ( ([depth, max]) => depth ? NaN : max ) ([...string].reduce(([depth, max], ch) => (newDepth => [newDepth, newDepth < 0 ? NaN : Math.max(max, newDepth)]) (depth + (ch === "(") - (ch === ")")) , [0, 0])); } console.log(maxDepth("(((()))(((())))()(((((()))))))")); 

這應該回答它!

 function balanceParens(string) { let max = 0; let res = string.split("").reduce((counter, char) => { // Handle if parens open and close out of order if (counter < 0) { return counter; } // Add 1 for each open in order if (char === "(") { if(++counter > max) { max = counter; } return counter; } // subtract 1 for each close in order if (char === ")") { return --counter; } // handle use case if char is not a paren return counter; }, 0); console.log("Max depth was :", max); return !res; } console.log(balanceParens("((()(((())))))((((()))))")); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM