Skip to content

Commit

Permalink
Merge pull request #35 from abhishektripathi66/abhishektripathi66-pat…
Browse files Browse the repository at this point in the history
…ch-1

Create LongestValidParentheses.java
  • Loading branch information
abhishektripathi66 authored Oct 30, 2024
2 parents dcd7528 + b036812 commit 0027009
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Leetcode/LongestValidParentheses.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
32. Longest Valid Parentheses
Solved
Hard
Topics
Companies
Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses
substring
.
*/
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int max_len = 0;

for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
max_len = Math.max(max_len, i - stack.peek());
}
}
}

return max_len;
}
}

0 comments on commit 0027009

Please sign in to comment.