Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.2 kB
2
Indexable
Never
// Online C++ compiler to run C++ program online
#include <bits/stdc++.h>
using namespace std;

int longestValidParentheses(string s) {
        stack<char> st;
        stack<int> st2;
        int check[10000];
        int index = 0;
        for (int i = 0 ; i < s.length(); i++) {
                if (s[i] == '(') {
                    st.push(s[i]);
                    st2.push(i);
                }
                if (s[i] == ')' && !st.empty() && !st2.empty()) {
                    check[index++] = st2.top();
                    st2.pop();
                    check[index++] = i;
                    st.pop();

                }
        }
        sort(check, check + index);
        int maxLength = 0;
        int lengthCurrent = 1;
        for (int i = 0 ; i < index; i++) {
            //cout << check[i] << " ";
            if (check[i+1] - check[i] == 1) {
                lengthCurrent++;
            } else {
                maxLength = max(maxLength, lengthCurrent);
                lengthCurrent = 1;
            }
        }
        
        return maxLength;
    }

int main() {
    string s = "())((";
    cout<< longestValidParentheses(s);
    // Write C++ code here

    return 0;
}
Leave a Comment