Advertisement
YEZAELP

LeetCode: Longest Valid Parentheses

Nov 17th, 2021
839
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int longestValidParentheses(string s) {
  4.         int sz = s.size();
  5.         stack <pair<char, int>> st;
  6.         for(int i=0;i<sz;i++){
  7.             int c = s[i];
  8.             if(c == '(') st.push({c, i});
  9.             else{
  10.                 if(!st.empty() and st.top().first == '(') st.pop();
  11.                 else st.push({c, i});
  12.             }
  13.         }
  14.         int mx = 0;
  15.         int pre = sz;
  16.         while(!st.empty()){
  17.             int cur = st.top().second; st.pop();
  18.             mx = max(mx, pre - cur - 1);
  19.             pre = cur;
  20.         }
  21.         mx = max(mx, pre);
  22.         return mx;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement