32. Longest Valid Parentheses 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 112345678910111213141516171819202122232425class Solution {public: int longestValidParentheses(string s) { stack<int> sta; int start = 0, ret= 0; for(int i=0;i<s.size();++i){ char c= s[i]; if(c=='('){ sta.push(i); } else{ if(sta.empty()) start = i+1; else{ sta.pop(); if(sta.empty()) ret = max(i-start+1, ret); else ret = max(ret, i- sta.top()); } } } return ret; }}; option 2 - dpoption 3 - Two Pointers , reduce dp