Parenthesis/Brackets Matching using Stack algorithm

前端 未结 30 2558
你的背包
你的背包 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<Character> stack = new Stack<Character>();
    
            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");
        }
    }
    
    0 讨论(0)
  • 2020-11-27 11:59
    import java.util.*;
    
    class StackDemo {
    
        public static void main(String[] argh) {
            boolean flag = true;
            String str = "(()){}()";
            int l = str.length();
            flag = true;
            Stack<String> st = new Stack<String>();
            for (int i = 0; i < l; i++) {
                String test = str.substring(i, i + 1);
                if (test.equals("(")) {
                    st.push(test);
                } else if (test.equals("{")) {
                    st.push(test);
                } else if (test.equals("[")) {
                    st.push(test);
                } else if (test.equals(")")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("(")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                } else if (test.equals("}")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("{")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                } else if (test.equals("]")) {
                    if (st.empty()) {
                        flag = false;
                        break;
                    }
                    if (st.peek().equals("[")) {
                        st.pop();
                    } else {
                        flag = false;
                        break;
                    }
                }
            }
            if (flag && st.empty())
                System.out.println("true");
            else
                System.out.println("false");
        }
    }
    
    0 讨论(0)
  • 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<Character> buffer = new Stack<Character>();
                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;
    }
    
    }
    
    0 讨论(0)
  • 2020-11-27 12:01

    in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)

    import java.util.Stack; 
    
        public static void main(String[] args) {
    
        //String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
        // Example: "()" is balanced
        // Example: "{ ]" is not balanced.
        // Examples: "()[]{}" is balanced.
        // "{([])}" is balanced
        // "{([)]}" is _not_ balanced
    
        String[] arrayOfBraces  = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
        String[] answers        = new String[arrayOfBraces.length];     
        String openers          = "([{";
        String closers          = ")]}";
        String stringToInspect  = ""; 
        Stack<String> stack     = new Stack<String>();
    
    
        for (int i = 0; i < arrayOfBraces.length; i++) {
    
            stringToInspect = arrayOfBraces[i];
            for (int j = 0; j < stringToInspect.length(); j++) {            
                if(stack.isEmpty()){
                    if (openers.indexOf(stringToInspect.charAt(j))>=0) {
                        stack.push(""+stringToInspect.charAt(j));   
                    }
                    else{
                        answers[i]= "NO";
                        j=stringToInspect.length();
                    }                   
                }
                else if(openers.indexOf(stringToInspect.charAt(j))>=0){
                    stack.push(""+stringToInspect.charAt(j));   
                }
                else{
                    String comparator = stack.pop();
                    int compLoc = openers.indexOf(comparator);
                    int thisLoc = closers.indexOf(stringToInspect.charAt(j));
    
                    if (compLoc != thisLoc) {
                        answers[i]= "NO";
                        j=stringToInspect.length();                     
                    }
                    else{
                        if(stack.empty() && (j== stringToInspect.length()-1)){
                            answers[i]= "YES";
                        }
                    }
                }
            }
        }
    
        System.out.println(answers.length);         
        for (int j = 0; j < answers.length; j++) {
            System.out.println(answers[j]);
        }       
    }
    
    0 讨论(0)
  • 2020-11-27 12:03

    You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:

    public static boolean isParenthesisMatch(String str) {
        Stack<Character> stack = new Stack<Character>();
        char c;
    
        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (c == '(' || c == '{')
                stack.push(c);
            else if (stack.empty())
                return false;
            else if (c == ')') {
                if (stack.pop() != '(')
                    return false;
            } else if (c == '}') {
                if (stack.pop() != '{')
                    return false;
            }
        }
        return stack.empty();
    }
    

    There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.

    0 讨论(0)
  • 2020-11-27 12:04
    //basic code non strack algorithm just started learning java ignore space and time.
    /// {[()]}[][]{}
    // {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))-> 
    //Split string to substring {[()]}, next [], next [], next{}
    
    public class testbrackets {
        static String stringfirst;
        static String stringsecond;
        static int open = 0;
        public static void main(String[] args) {
            splitstring("(()){}()");
        }
    static void splitstring(String str){
    
        int len = str.length();
        for(int i=0;i<=len-1;i++){
            stringfirst="";
            stringsecond="";
            System.out.println("loop starttttttt");
            char a = str.charAt(i);
        if(a=='{'||a=='['||a=='(')
        {
            open = open+1;
            continue;
        }
        if(a=='}'||a==']'||a==')'){
            if(open==0){
                System.out.println(open+"started with closing brace");
                return;
            }
            String stringfirst=str.substring(i-open, i);
            System.out.println("stringfirst"+stringfirst);
            String stringsecond=str.substring(i, i+open);
            System.out.println("stringsecond"+stringsecond);
            replace(stringfirst, stringsecond);
    
            }
        i=(i+open)-1;
        open=0;
        System.out.println(i);
        }
        }
        static void replace(String stringfirst, String stringsecond){
            stringfirst = stringfirst.replace('{', '}');
            stringfirst = stringfirst.replace('(', ')');
            stringfirst = stringfirst.replace('[', ']');
            StringBuilder stringfirst1 = new StringBuilder(stringfirst);
            stringfirst = stringfirst1.reverse().toString();
        System.out.println("stringfirst"+stringfirst);
        System.out.println("stringsecond"+stringsecond);
    if(stringfirst.equals(stringsecond)){
        System.out.println("pass");
    }
        else{
            System.out.println("fail");
            System.exit(0);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题