Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. public class Solution {
  2.     public int longestValidParentheses(String s) {
  3.         int left = 0, right = 0, maxlength = 0;
  4.         for (int i = 0; i < s.length(); i++) {
  5.             if (s.charAt(i) == '(') {
  6.                 left++;
  7.             } else {
  8.                 right++;
  9.             }
  10.             if (left == right) {
  11.                 maxlength = Math.max(maxlength, 2 * right);
  12.             } else if (right >= left) {
  13.                 left = right = 0;
  14.             }
  15.         }
  16.         left = right = 0;
  17.         for (int i = s.length() - 1; i >= 0; i--) {
  18.             if (s.charAt(i) == '(') {
  19.                 left++;
  20.             } else {
  21.                 right++;
  22.             }
  23.             if (left == right) {
  24.                 maxlength = Math.max(maxlength, 2 * left);
  25.             } else if (left >= right) {
  26.                 left = right = 0;
  27.             }
  28.         }
  29.         return maxlength;
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement