Skip to content

Commit

Permalink
add khushal87 longest_valid_paranthesis
Browse files Browse the repository at this point in the history
  • Loading branch information
khushal87 committed Jan 20, 2021
1 parent 90fc86f commit bbfcb43
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Stack/longest_valid_paranthesis.c++
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <bits/stdc++.h>
using namespace std;

int lengthOfLongestValidParanthesis(string s)
{
int n = s.length();
stack<int> st;
st.push(-1);

int result = 0;
for (int i = 0; i < n; i++)
{
if (s[i] == '(')
{
st.push(i);
}
else
{
if (!st.empty())
{
st.pop();
}
if (!st.empty())
{
result = max(result, i - st.top());
}
else
{
st.push(i);
}
}
}
return result;
}

int main()
{
string s;
cin >> s;
int ans = lengthOfLongestValidParanthesis(s);
cout << "Length = " << ans << endl;
}

0 comments on commit bbfcb43

Please sign in to comment.