leetcode 32 最長有效括號

2021-10-07 18:25:25 字數 843 閱讀 9258

題目鏈結

給定乙個只包含 『(』 和 『)』 的字串,找出最長的包含有效括號的子串的長度。

class

solution

int res =0;

vector<

int>

flags

(len,0)

;for

(int i =

0; i < len;

++i)

int left =1;

for(

int loc = i +1;

(left !=0)

&&(loc < len)

;++loc)

else}}

}return res;}}

;

執行結果:通過

執行用時:1332 ms, 在所有 c++ 提交中擊敗了5.21%的使用者

記憶體消耗:7.6 mb, 在所有 c++ 提交中擊敗了100.00%的使用者

本道題我是先求以每個左括號為起點的有效括號個數,然後儲存flag陣列內。

class

solution

}else

if(dp[i -1]

>0)

}}} maxval =

max(maxval, dp[i]);

}return maxval;}}

;

參考官方解答。

LeetCode 32 最長有效括號

思路 自己沒想出來,參考了一下網上大神的提示。使用乙個int棧,將左括號記為 1,右括號記為 2 遍歷字串。1.若為 則直接壓入棧 2.若為 分情況討論 若棧頂為 2 或棧空,則直接將 2壓入棧 若棧容量為1,且棧頂為 1,將 1推出棧,推入2,代表此時有一對匹配括號 若棧容量為1,且棧頂大於0,說...

leetcode 32 最長有效括號

一 先對字串進行遍歷 首先從前往後排除不配對的 首次遍歷後的字串被分成若干個字串 再對這些字串 從後往前排除不配對的 int longestvalidparentheses std string s else if s j else t1 j 1 n 0 continue if max2 n max...

LeetCode32 最長有效括號

題目鏈結 500 800ms class solution else if s j for int i 0 ilength i if s i 0 result 0 if result k return result else return k 這絕不是最優解 幾十毫秒之內解決問題 class sol...