Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2562
你的背包
你的背包 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条回答
  • 2020-11-27 12:20

    Ganesan's answer above is not correct and StackOverflow is not letting me comment or Edit his post. So below is the correct answer. Ganesan has an incorrect facing "[" and is missing the stack isEmpty() check.

    The below code will return true if the braces are properly matching.

    public static boolean isValidExpression(String expression) {
        Map<Character, Character> openClosePair = new HashMap<Character, Character>();
        openClosePair.put(')', '(');
        openClosePair.put('}', '{');
        openClosePair.put(']', '[');
    
        Stack<Character> stack = new Stack<Character>();
        for(char ch : expression.toCharArray()) {
            if(openClosePair.containsKey(ch)) {
                if(stack.isEmpty() || stack.pop() != openClosePair.get(ch)) {
                    return false;
                }
            } else if(openClosePair.values().contains(ch)) {
                stack.push(ch); 
            }
        }
        return stack.isEmpty();
    }
    
    0 讨论(0)
  • 2020-11-27 12:22

    here is my solution using c++ if brackets are matched then returns true if not then gives false

    #include <iostream>
    #include <stack>
    #include <string.h>
    using namespace std;
    
    int matchbracket(string expr){
        stack<char> st;
        int i;
        char x;
        for(i=0;i<expr.length();i++){
            if(expr[i]=='('||expr[i]=='{'||expr[i]=='[')
              st.push(expr[i]);
              
            if(st.empty())
             return -1;
            switch(expr[i]){
                case ')' :
                 x=expr[i];
                 st.pop();
                 if(x=='}'||x==']')
                  return 0;
                  break;
                
                case '}' :
                 x=expr[i];
                 st.pop();
                 if(x==')'||x==']')
                  return 0;
                  break;
            
                case ']' :
                x=expr[i];
                st.pop();
                if(x==')'||x=='}')
                 return 1;
                 break;
            } 
    
        }
        return(st.empty());
    }
    
    int main()
    {
     string expr;
     cin>>expr;
     
     if(matchbracket(expr)==1)
      cout<<"\nTRUE\n";
      else
      cout<<"\nFALSE\n";
    }
    
    0 讨论(0)
  • 2020-11-27 12:23
    public static bool IsBalanced(string input)
        {
            Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
            { '(', ')' },
            { '{', '}' },
            { '[', ']' },
            { '<', '>' }
        };
    
            Stack<char> brackets = new Stack<char>();
    
            try
            {
                // Iterate through each character in the input string
                foreach (char c in input)
                {
                    // check if the character is one of the 'opening' brackets
                    if (bracketPairs.Keys.Contains(c))
                    {
                        // if yes, push to stack
                        brackets.Push(c);
                    }
                    else
                        // check if the character is one of the 'closing' brackets
                        if (bracketPairs.Values.Contains(c))
                        {
                            // check if the closing bracket matches the 'latest' 'opening' bracket
                            if (c == bracketPairs[brackets.First()])
                            {
                                brackets.Pop();
                            }
                            else
                                // if not, its an unbalanced string
                                return false;
                        }
                        else
                            // continue looking
                            continue;
                }
            }
            catch
            {
                // an exception will be caught in case a closing bracket is found, 
                // before any opening bracket.
                // that implies, the string is not balanced. Return false
                return false;
            }
    
            // Ensure all brackets are closed
            return brackets.Count() == 0 ? true : false;
        }
    
    0 讨论(0)
  • 2020-11-27 12:23
      Check balanced parenthesis or brackets with stack-- 
      var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
       var stk = [];   
       function bracket_balance(){
          for(var i=0;i<excp.length;i++){
              if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
                 stk.push(excp[i]);
              }else if(excp[i]== ']' && stk.pop() != '['){
                 return false;
              }else if(excp[i]== '}' && stk.pop() != '{'){
    
                return false;
              }else if(excp[i]== ')' && stk.pop() != '('){
    
                return false;
              }
          }
    
          return true;
       }
    
      console.log(bracket_balance());
      //Parenthesis are balance then return true else false
    
    0 讨论(0)
  • 2020-11-27 12:24

    I think is the best answer:

    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        Stack<Character> stack = new Stack<>();
        for(char c : s.toCharArray()){
            if(map.containsKey(c)){
                stack.push(c);
            } else if(!stack.empty() && map.get(stack.peek())==c){
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.empty();
    }
    
    0 讨论(0)
  • 2020-11-27 12:25

    Actually, there is no need to check any cases "manually". You can just run the following algorithm:

    1. Iterate over the given sequence. Start with an empty stack.

    2. If the current char is an opening bracket, just push it to the stack.

    3. If it's a closing bracket, check that the stack is not empty and the top element of the step is an appropriate opening bracket(that it is, matches this one). If it is not, report an error. Otherwise, pop the top element from the stack.

    4. In the end, the sequence is correct iff the stack is empty.

    Why is it correct? Here is a sketch of a proof: if this algorithm reported that the sequence is corrected, it had found a matching pair of all brackets. Thus, the sequence is indeed correct by definition. If it has reported an error:

    1. If the stack was not empty in the end, the balance of opening and closing brackets is not zero. Thus, it is not a correct sequence.

    2. If the stack was empty when we had to pop an element, the balance is off again.

    3. If there was a wrong element on top of the stack, a pair of "wrong" brackets should match each other. It means that the sequence is not correct.

    I have shown that:

    • If the algorithm has reported that the sequence is correct, it is correct.

    • If the algorithm has reported that the sequence is not correct, it is incorrect(note that I do not use the fact that there are no other cases except those that are mentioned in your question).

    This two points imply that this algorithm works for all possible inputs.

    0 讨论(0)
提交回复
热议问题