查詢 JavaScript 中最長的有效括號


給定一個僅包含字元“(”和“)”的字串,我們找到最長的有效(形式良好)括號子串的長度。

一個括號集合的資格為形式良好的括號,當且僅當每個開括號包含一個尾括號。

例如:

'(())()' is a well-formed parentheses
'())' is not a well-formed parentheses
'()()()' is a well-formed parentheses

示例

const str = '(())()(((';
   const longestValidParentheses = (str = '') => {
      var ts = str.split('');
      var stack = [], max = 0;
      ts.forEach((el, ind) => {
         if (el == '(') {
            stack.push(ind);
         }
      else {
         if (stack.length === 0 || ts[stack[stack.length - 1]] == ')'){
            stack.push(ind);
         }
         else {
            stack.pop();
         };
      }
   });
   stack.push(ts.length);
   stack.splice(0, 0, -1);
   for (let ind = 0;
   ind< stack.length - 1; ind++) {
      let v = stack[ind+1] - stack[ind] - 1; max = Math.max(max, v);
   };
   return max;
}; console.log(longestValidParentheses(str));

輸出

控制檯中的輸出為:

6

更新:2020 年 11 月 23 日

259 次瀏覽

開啟您的職業

完成該課程可獲得認證

開始
廣告