Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.web.webserver;
- public class Oloolo {
- public static void main(String[] args) {
- char exp[] = "{()}[<>saa]".toCharArray();
- if (areParenthesisBalanced(exp)) {
- System.out.printf("\n Balanced ");
- } else {
- System.out.printf("\n Not Balanced ");
- }
- }
- private static boolean areParenthesisBalanced(char exp[]) {
- Stack stack = new Stack();
- for (char anExp : exp) {
- if (anExp == '{' || anExp == '(' || anExp == '[' || anExp == '<') {
- push(stack, anExp);
- }
- if (anExp == '}' || anExp == ')' || anExp == ']' || anExp == '>') {
- if (stack.head == null) {
- return false;
- } else if (!isMatchingPair((char) pop(stack), anExp)) {
- return false;
- }
- }
- }
- return stack.head == null;
- }
- private static boolean isMatchingPair(char character1, char character2) {
- return character1 == '(' && character2 == ')' || character1 == '{' && character2 == '}' || character1 == '[' && character2 == ']' || character1 == '<' && character2 == '>';
- }
- private static int pop(Stack top_ref) {
- char res;
- Node top;
- if (top_ref == null) {
- System.out.printf("Stack overflow \n");
- System.exit(0);
- return 0;
- } else {
- top = top_ref.head;
- res = top.data;
- top_ref.head = top.next;
- return res;
- }
- }
- private static void push(Stack top_ref, int new_data) {
- Node new_node = new Node();
- new_node.data = (char) new_data;
- new_node.next = top_ref.head;
- top_ref.head = new_node;
- }
- private static class Node {
- public Node next;
- public char data;
- }
- private static class Stack {
- public Node head;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement