Guest User

Untitled

a guest
Oct 18th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class BracketMatch {
  5.  
  6. static int bracketMatch(String text) {
  7. if (text == null || text.isEmpty()) {
  8. throw new IllegalArgumentException("Provide a text");
  9. }
  10. if (!text.replaceAll("[()]", "").isEmpty()) {
  11. throw new IllegalArgumentException("Found invalid character");
  12. }
  13.  
  14. int count = 0;
  15. int orphanCloseBracket = 0;
  16. for (int idx = 0; idx < text.length(); idx++) {
  17. if (text.charAt(idx) == '(') {
  18. count++;
  19. } else {
  20. if (count == 0) {
  21. orphanCloseBracket++;
  22. } else if (count > 0 ) {
  23. count--;
  24. }
  25. }
  26. }
  27. return count+orphanCloseBracket;
  28. }
  29.  
  30. public static void main(String[] args) {
  31.  
  32. System.out.println(bracketMatch("(()")); // 1
  33. System.out.println(bracketMatch("(())")); // 0
  34. System.out.println(bracketMatch("())(")); // 2
  35. }
  36. }
  37. /*
  38.  
  39. text = "())("
  40. n=0
  41. ---------+
  42. (| push
  43. ---------+
  44. n=1
  45. ---------+
  46. | pop
  47. ---------+
  48. n=2
  49. ---------+
  50. | orphanCloseBracket : 1
  51. ---------+
  52. n=3
  53. ---------+
  54. )| push
  55. ---------+
  56. openBracketSize: 1
  57.  
  58. text = "(())"
  59. n=0
  60. ---------+
  61. (| push
  62. ---------+
  63. n=1
  64. ---------+
  65. ((| push
  66. ---------+
  67. n=2
  68. ---------+
  69. (| pop
  70. ---------+
  71. n=3
  72. ---------+
  73. | pop
  74. ---------+
  75. openBracketSize: 0
  76.  
  77. */
Add Comment
Please, Sign In to add comment