Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2559
你的背包
你的背包 2020-11-27 11:39

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

and so on but if the parenthesis/brackets is not mat

相关标签:
30条回答
  • Algorithm is:

    1)Create a stack
    
    2)while(end of input is not reached)
    
       i)if the character read is not a sysmbol to be balanced ,ignore it.
    
       ii)if the character is {,[,( then push it to stack
    
       iii)If it is a },),] then if 
    
            a)the stack is empty report an error(catch it) i.e not balanced
    
            b)else pop the stack 
    
       iv)if element popped is not corresponding to opening sysmbol,then report error.
    
    3) In the end,if stack is not empty report error else expression is balanced.  
    

    In Java code:

    public class StackDemo {
        public static void main(String[] args) throws Exception {
            System.out.println("--Bracket checker--");
            CharStackArray stack = new CharStackArray(10);
            stack.balanceSymbol("[a+b{c+(e-f[p-q])}]") ;
            stack.display();
    
        }
    
    }    
    
    class CharStackArray {
            private char[] array;
            private int top;
            private int capacity;
    
            public CharStackArray(int cap) {
                capacity = cap;
                array = new char[capacity];
                top = -1;
            }
    
            public void push(char data) {
                array[++top] = data;
            }
    
            public char pop() {
                return array[top--];
            }
    
            public void display() {
                for (int i = 0; i <= top; i++) {
                    System.out.print(array[i] + "->");
                }
            }
    
            public char peek() throws Exception {
                return array[top];
            }
    
            /*Call this method by passing a string expression*/
            public void balanceSymbol(String str) {
                try {
                    char[] arr = str.toCharArray();
                    for (int i = 0; i < arr.length; i++) {
                        if (arr[i] == '[' || arr[i] == '{' || arr[i] == '(')
                            push(arr[i]);
                        else if (arr[i] == '}' && peek() == '{')
                            pop();
                        else if (arr[i] == ']' && peek() == '[')
                            pop();
                        else if (arr[i] == ')' && peek() == '(')
                            pop();
                    }
                    if (isEmpty()) {
                        System.out.println("String is balanced");
                    } else {
                        System.out.println("String is not balanced");
                    }
                } catch (Exception e) {
                    System.out.println("String not balanced");
                }
    
            }
    
            public boolean isEmpty() {
                return (top == -1);
            }
        }
    

    Output:

    --Bracket checker--

    String is balanced

    0 讨论(0)
  • 2020-11-27 12:18

    Optimized implementation using Stacks and Switch statement:

    public class JavaStack {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    
          Stack<Character> s = new Stack<Character>();
    
        while (sc.hasNext()) {
            String input = sc.next();
    
            for (int i = 0; i < input.length(); i++) {
                char c = input.charAt(i);
                switch (c) {
    
                    case '(':
                        s.push(c); break;
                    case '[':
                        s.push(c); break;
                    case '{':
                        s.push(c); break;
                    case ')':
                        if (!s.isEmpty() && s.peek().equals('(')) {
                            s.pop();
                        } else {
                            s.push(c);
                        } break;
                    case ']':
                        if (!s.isEmpty() && s.peek().equals('[')) {
                            s.pop();
                        } else {
                            s.push(c);
                        } break;
                    case '}':
                        if (!s.isEmpty() && s.peek().equals('{')) {
                            s.pop();
                        } else {
                            s.push(c);
                        } break;
    
                    default:
                        s.push('x'); break;
    
                }
    
            }
            if (s.empty()) {
                System.out.println("true");
            } else {
                System.out.println("false");
                s.clear();
            }
        }
    } }
    

    Cheers !

    0 讨论(0)
  • 2020-11-27 12:18

    Algorithm to use for checking well balanced parenthesis -

    1. Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
    2. Declare a set openingParenSet and initialize it with the values of matchingParenMap.
    3. Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
    4. Now traverse the string expression input.

      1. If the current character is an opening bracket ( '{', '(', '[' ) then push it to the parenStack.

      2. If the current character is a closing bracket ( '}', ')', ']' ) then pop from parenStack and if the popped character is equal to the matching starting bracket in matchingParenMap then continue looping else return false.

    5. After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.

    I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/

    0 讨论(0)
  • 2020-11-27 12:18
    import java.util.*;
    
    public class Parenthesis
    
     {
    
        public static void main(String...okok)
    
        {
            Scanner sc= new Scanner(System.in);
            String str=sc.next();
            System.out.println(isValid(str));
    
        }
        public static int isValid(String a) {
            if(a.length()%2!=0)
            {
    
                return 0;
            }
            else if(a.length()==0)
            {
    
                return 1;
            }
            else
            {
    
                char c[]=a.toCharArray();
                Stack<Character> stk =  new Stack<Character>();
                for(int i=0;i<c.length;i++)
                {
                    if(c[i]=='(' || c[i]=='[' || c[i]=='{')
                    {
                        stk.push(c[i]);
                    }
                    else
                    {
                        if(stk.isEmpty())
                        {
                            return 0;
                            //break;
                        }
                        else
                        {
    
                            char cc=c[i];
                            if(cc==')' && stk.peek()=='(' )
                            {
                                stk.pop();
                            }
                            else if(cc==']' && stk.peek()=='[' )
                            {
    
                                stk.pop();
                            }
                            else if(cc=='}' && stk.peek()=='{' )
                            {
    
                                stk.pop();
                            }
                        }
                    }
    
                }
                if(stk.isEmpty())
                {
                    return 1;
                }else
                {
                    return 0;
                }
            }
    
    
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 12:18

    I tried this using javascript below is the result.

    function bracesChecker(str) {
      if(!str) {
        return true;
      }
      var openingBraces = ['{', '[', '('];
      var closingBraces = ['}', ']', ')'];
      var stack = [];
      var openIndex;
      var closeIndex;
      //check for opening Braces in the val
      for (var i = 0, len = str.length; i < len; i++) {
        openIndex = openingBraces.indexOf(str[i]);
        closeIndex = closingBraces.indexOf(str[i]);
        if(openIndex !== -1) {
          stack.push(str[i]);
        }  
        if(closeIndex !== -1) {
          if(openingBraces[closeIndex] === stack[stack.length-1]) { 
            stack.pop();
          } else {
            return false;
          }
        }
      }
      if(stack.length === 0) {
        return true;
      } else {
        return false;
      }
    }
    var testStrings = [
      '', 
      'test', 
      '{{[][]()()}()}[]()', 
      '{test{[test]}}', 
      '{test{[test]}', 
      '{test{(yo)[test]}}', 
      'test{[test]}}', 
      'te()s[]t{[test]}', 
      'te()s[]t{[test'
    ];
    
    testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
    
    0 讨论(0)
  • 2020-11-27 12:18

    If you want to have a look at my code. Just for reference

    public class Default {
    
        public static void main(String[] args) throws IOException {
    
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int numOfString = Integer.parseInt(br.readLine());
            String s;
            String stringBalanced = "YES";
            Stack<Character> exprStack = new Stack<Character>();
    
            while ((s = br.readLine()) != null) {
                stringBalanced = "YES";
                int length = s.length() - 1;
                for (int i = 0; i <= length; i++) {
                    char tmp = s.charAt(i);
    
                    if(tmp=='[' || tmp=='{' || tmp=='('){
                        exprStack.push(tmp);
                    }else if(tmp==']' || tmp=='}' || tmp==')'){
                        if(!exprStack.isEmpty()){
                            char peekElement = exprStack.peek();
                            exprStack.pop();
                            if(tmp==']' && peekElement!='['){
                                stringBalanced="NO";
                            }else if(tmp=='}' && peekElement!='{'){
                                stringBalanced="NO";
                            }else if(tmp==')' && peekElement!='('){
                                stringBalanced="NO";
                            }
                        }else{
                            stringBalanced="NO";
                            break;
                        }
                    }
    
                }
    
                if(!exprStack.isEmpty()){
                    stringBalanced = "NO";
                }
    
                exprStack.clear();
                System.out.println(stringBalanced);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题