Parenthesis/Brackets Matching using Stack algorithm

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

    package com.balance.braces;
    
    import java.util.Arrays;
    import java.util.Stack;
    
    public class BalanceBraces {
    
    public static void main(String[] args) {
    
        String[] values = { "()]", "[()]" };
    
        String[] rsult = match(values);
    
        Arrays.stream(rsult).forEach(str -> System.out.println(str));
    }
    
    static String[] match(String[] values) {
    
        String[] returnString = new String[values.length];
    
        for (int i = 0; i < values.length; i++) {
            String value = values[i];
    
            if (value.length() % 2 != 0) {
                returnString[i] = "NO";
                continue;
            } else {
    
                Stack buffer = new Stack();
                for (char ch : value.toCharArray()) {
    
                    if (buffer.isEmpty()) {
                        buffer.add(ch);
                    } else {
                        if (isMatchedBrace(buffer.peek(), ch)) {
                            buffer.pop();
                        } else {
                            buffer.push(ch);
                        }
                    }
                    if (buffer.isEmpty()) {
                        returnString[i] = "YES";
                    } else {
                        returnString[i] = "FALSE";
                    }
                }
            }
    
        }
    
        return returnString;
    }
    
    static boolean isMatchedBrace(char start, char endmatch) {
        if (start == '{')
            return endmatch == '}';
        if (start == '(')
            return endmatch == ')';
        if (start == '[')
            return endmatch == ']';
        return false;
    }
    
    }
    

提交回复
热议问题