fork(1) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Ideone
  7. {
  8. private int getLongestParenthesisLength(String str) {
  9. Stack<Integer> stack = new Stack<Integer>();
  10. int n = str.length();
  11. int length = 0;
  12. int lastMatchedIndex = -1;
  13. for (int i = 0; i < n; i++) {
  14. char ch = str.charAt(i);
  15. switch (ch) {
  16. case '(':
  17. stack.push(i);
  18. break;
  19. case ')':
  20. if (stack.isEmpty()) {
  21. lastMatchedIndex = i;
  22. } else {
  23. stack.pop();
  24. if (stack.isEmpty()) {
  25. length = Math.max(length, i - lastMatchedIndex);
  26. } else {
  27. length = Math.max(length, i - stack.peek());
  28. }
  29. }
  30. break;
  31. }
  32. }
  33. return length;
  34. }
  35. public static void main (String[] args) throws java.lang.Exception
  36. {
  37. Ideone longestParenthesis = new Ideone();
  38. Scanner sc = new Scanner(System.in);
  39. String str = sc.next();
  40. int len = longestParenthesis.getLongestParenthesisLength(str);
  41. System.out.println(len);
  42. }
  43. }
Success #stdin #stdout 0.09s 2841600KB
stdin
((())
stdout
4