fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3.  
  4. class CountLongestBalanced {
  5. public static void main(String[] args) {
  6. String[] testCases = {"(()", ")()())", "((()()", "((()(()()", "(())(()", "())()()"};
  7. for (String s : testCases) {
  8. System.out.printf("%s -> %d\n", s, countLongestBalanced(s, 0));
  9. }
  10. }
  11.  
  12. static int countLongestBalanced(String str, int start) {
  13. if ((str.length() - start) <= 1) return 0;
  14. int longestN = 0;
  15. int curN = 0;
  16. int count = 0;
  17. int lastRunStart = 0;
  18. for (int i = start; i < str.length(); ++i) {
  19. switch(str.charAt(i)) {
  20. case '(': ++count; break;
  21. case ')': --count; break;
  22. default: continue;
  23. }
  24. ++curN;
  25. if (count == 0) {
  26. longestN = Math.max(curN, longestN);
  27. lastRunStart = i + 1;
  28. } else if (count < 0) {
  29. //bad balance, start over
  30. curN = 0;
  31. count = 0;
  32. lastRunStart = i + 1;
  33. }
  34. }
  35. if (count == 0) longestN = Math.max(curN, longestN);
  36. else if (count > 0) { //"save" unbalance for extra open pars by skipping them
  37. int i = lastRunStart;
  38. for (; i < str.length() && count > 0; ++i) {
  39. if (str.charAt(i) == '(') --count;
  40. else if (str.charAt(i) == ')') ++count;
  41. }
  42. if (i < str.length()) {
  43. //Note: this will be called only once (no deeper recursion)
  44. longestN = Math.max(longestN, countLongestBalanced(str, i));
  45. }
  46. }
  47. return longestN;
  48. }
  49. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
(() -> 2
)()()) -> 4
((()() -> 4
((()(()() -> 4
(())(() -> 4
())()() -> 4