Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. package com.web.webserver;
  2.  
  3. public class Oloolo {
  4.  
  5. public static void main(String[] args) {
  6. char exp[] = "{()}[<>saa]".toCharArray();
  7. if (areParenthesisBalanced(exp)) {
  8. System.out.printf("\n Balanced ");
  9. } else {
  10. System.out.printf("\n Not Balanced ");
  11. }
  12. }
  13.  
  14. private static boolean areParenthesisBalanced(char exp[]) {
  15. Stack stack = new Stack();
  16.  
  17. for (char anExp : exp) {
  18. if (anExp == '{' || anExp == '(' || anExp == '[' || anExp == '<') {
  19. push(stack, anExp);
  20. }
  21. if (anExp == '}' || anExp == ')' || anExp == ']' || anExp == '>') {
  22. if (stack.head == null) {
  23. return false;
  24. } else if (!isMatchingPair((char) pop(stack), anExp)) {
  25. return false;
  26. }
  27. }
  28. }
  29.  
  30. return stack.head == null;
  31. }
  32.  
  33. private static boolean isMatchingPair(char character1, char character2) {
  34. return character1 == '(' && character2 == ')' || character1 == '{' && character2 == '}' || character1 == '[' && character2 == ']' || character1 == '<' && character2 == '>';
  35. }
  36.  
  37. private static int pop(Stack top_ref) {
  38. char res;
  39. Node top;
  40.  
  41. if (top_ref == null) {
  42. System.out.printf("Stack overflow \n");
  43. System.exit(0);
  44. return 0;
  45. } else {
  46. top = top_ref.head;
  47. res = top.data;
  48. top_ref.head = top.next;
  49. return res;
  50. }
  51. }
  52.  
  53. private static void push(Stack top_ref, int new_data) {
  54. Node new_node = new Node();
  55. new_node.data = (char) new_data;
  56. new_node.next = top_ref.head;
  57. top_ref.head = new_node;
  58. }
  59.  
  60. private static class Node {
  61. public Node next;
  62. public char data;
  63. }
  64.  
  65. private static class Stack {
  66. public Node head;
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement