Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2560
你的背包
你的背包 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:05

    The algorithm:

    1. scan the string,pushing to a stack for every '(' found in the string
    2. if char ')' scanned, pop one '(' from the stack

    Now, parentheses are balanced for two conditions:

    • '(' can be popped from the stack for every ')' found in the string, and
    • stack is empty at the end (when the entire string is processed)
    0 讨论(0)
  • 2020-11-27 12:07

    Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.

    This code, modified slightly from yours, seems to work properly:

    public static boolean isParenthesisMatch(String str) {
        if (str.charAt(0) == '{')
            return false;
    
        Stack<Character> stack = new Stack<Character>();
    
        char c;
        for(int i=0; i < str.length(); i++) {
            c = str.charAt(i);
    
            if(c == '(')
                stack.push(c);
            else if(c == '{')
                stack.push(c);
            else if(c == ')')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
            else if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
    }
    
    0 讨论(0)
  • 2020-11-27 12:07
    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.pop() != openClosePair.get(ch)) {
                    return false;
                }
            } else if(openClosePair.values().contains(ch)) {
                stack.push(ch); 
            }
        }
        return stack.isEmpty();
    }
    
    0 讨论(0)
  • 2020-11-27 12:08

    This code is easier to understand:

    public static boolean CheckParentesis(String str)
    {
        if (str.isEmpty())
            return true;
    
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < str.length(); i++)
        {
            char current = str.charAt(i);
            if (current == '{' || current == '(' || current == '[')
            {
                stack.push(current);
            }
    
    
            if (current == '}' || current == ')' || current == ']')
            {
                if (stack.isEmpty())
                    return false;
    
                char last = stack.peek();
                if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                    stack.pop();
                else 
                    return false;
            }
    
        }
    
        return stack.isEmpty();
    }
    
    0 讨论(0)
  • 2020-11-27 12:08

    Problem Statement: Check for balanced parentheses in an expression Or Match for Open Closing Brackets

    If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure Solution in C#

            public void OpenClosingBracketsMatch()
            {
                string pattern = "{[(((((}}])";
                Dictionary<char, char> matchLookup = new Dictionary<char, char>();
                matchLookup['{'] = '}';
                matchLookup['('] = ')';
                matchLookup['['] = ']';
                Stack<char> stck = new Stack<char>();
                for (int i = 0; i < pattern.Length; i++)
                {
                    char currentChar = pattern[i];
                    if (matchLookup.ContainsKey(currentChar))
                        stck.Push(currentChar);
                    else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
                    {
                        char topCharFromStack = stck.Peek();
                        if (matchLookup[topCharFromStack] != currentChar)
                        {
                            Console.WriteLine("NOT Matched");
                            return;
                        }
                    }
                }
    
                Console.WriteLine("Matched");
            }
    

    For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/

    0 讨论(0)
  • 2020-11-27 12:08
    public String checkString(String value) {
        Stack<Character> stack = new Stack<>();
        char topStackChar = 0;
        for (int i = 0; i < value.length(); i++) {
            if (!stack.isEmpty()) {
                topStackChar = stack.peek();
            }
            stack.push(value.charAt(i));
            if (!stack.isEmpty() && stack.size() > 1) {
                if ((topStackChar == '[' && stack.peek() == ']') ||
                        (topStackChar == '{' && stack.peek() == '}') ||
                        (topStackChar == '(' && stack.peek() == ')')) {
                    stack.pop();
                    stack.pop();
                }
            }
        }
        return stack.isEmpty() ? "YES" : "NO";
    }
    
    0 讨论(0)
提交回复
热议问题