diff --git a/C++/longest_valid_parenthesis.cpp b/C++/longest_valid_parenthesis.cpp new file mode 100644 index 0000000..00398ae --- /dev/null +++ b/C++/longest_valid_parenthesis.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +class Solution { +public: + int longestValidParentheses(string s) { + stack st; + int result = 0, previous = -1; + + for (int i = 0; i < s.size(); i++) { + + if (s[i] == '(') st.push(i); + + else { + if (!st.empty()) { + st.pop(); + if (st.empty()) result = max(result, i - previous); + else result = max(result, i - st.top()); + } + else previous = i; + } + } + + return result; + } + + +}; + + +int main() { + Solution s; + cout<