Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2770
你的背包
你的背包 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 11:58

    import java.util.*;
    
    public class MatchBrackets {
    
        public static void main(String[] argh) {
            String input = "[]{[]()}";
            System.out.println  (input);
    
            char [] openChars =  {'[','{','('};
            char [] closeChars = {']','}',')'};
    
            Stack stack = new Stack();
    
            for (int i = 0; i < input.length(); i++) {
    
                String x = "" +input.charAt(i);
    
                if (String.valueOf(openChars).indexOf(x) != -1)
                {
                    stack.push(input.charAt(i));
                }
                else
                {
                    Character lastOpener = stack.peek();
                    int idx1 = String.valueOf(openChars).indexOf(lastOpener.toString());
                    int idx2 = String.valueOf(closeChars).indexOf(x);
    
                    if (idx1 != idx2)
                    {
                        System.out.println("false");
                        return;
                    }
                    else
                    {
                        stack.pop();
                    }
                }
            }
    
            if (stack.size() == 0)
                System.out.println("true");
            else
                System.out.println("false");
        }
    }
    

提交回复
热议问题