Checking string has balanced parentheses

后端 未结 18 2331
谎友^
谎友^ 2020-12-01 08:42

I am reading the Algorithm Design Manual Second Edition and this is from an exercise question. Quoting the question

A common problem for comp

相关标签:
18条回答
  • 2020-12-01 09:04
    Checking balanced parentheses
    package parancheck;
    
    import java.util.EmptyStackException;
    import java.util.Stack;
    
    public class ParnCheck 
    {
        public static void main(String args[])
        {
            int pu = 0;
            int po = 0;
            String str = "()())";
            System.out.println(str); 
            Stack st = new Stack();
           for(int i=0; i<str.length();i++)
           {
            if(str.charAt(i)=='(')
            {
               doPush(st, str.charAt(i));
               pu++;
             }
            else 
            {
                 try
                  {
                    doPop(st);
                  }
                 catch(EmptyStackException e)
                  {
                    System.out.println("");
                  }
                  po++;
            }
         }
    
    
           if(pu == po)
           {
               System.out.println("Correct");
           }
           else
           {
               System.out.println("Wrong");
           }
    
        }
        static void doPush(Stack st,char ch)
        {
            st.push(ch);
        }
        static void doPop(Stack st)
        {
            char c = (char)st.pop();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 09:07

    I think this is the intention, but really you just need to decrement and increment a counter if you are only dealing with parenthesis. If you are dealing with the pairings of square brackets, angle brackets, curly braces or whatever character pairing you'd like to use, you'll need a stack like you have done.

    You can also use a list, pulling the head element off and on, but really a stack is probably implemented as a list anyway --at least it is in ocaml.

    0 讨论(0)
  • 2020-12-01 09:09

    Here is simple solution to validate the brackets :
    1. Keep Starting brackets and Ending brackets in a string.
    2. Loop through given to whom we want to validate and check for following logic :

                  a) If item is in starting brackets, PUSH IT IN STACK
                  b) If item is in ending brackets, Compare its index(in ending bracket) with stack's top item                   index (in starting brackets).
                  c) If index are same POP TOP ITEM OF STACK. Else its Invalid string.
                  d) Final step, check for stack if it has item/s, it means its invalid string.

        string starters = "({[<";
        string enders = ")}]>";
        Stack stack  = new Stack();
        foreach(char c in txtValue.Text.Trim())
        {
            if(starters.Contains(c))
            {
                stack.Push(c);
            }
            else if (enders.Contains(c))
            {
                if (stack.Count > 0)
                {
    
                    if (enders.IndexOf(c) == starters.IndexOf(Convert.ToChar(stack.Peek())))
                    {
                        stack.Pop();
                    }
                    else
                    {
                        lblResult.Text = "Invaluid string";
                    }
                }
            }
        }
    
        if(stack.Count == 0)
        {
            lblResult.Text = "Valid string";
        }
        else
        {
            lblResult.Text = "InValid string";
        }
    
    0 讨论(0)
  • 2020-12-01 09:10

    This will work for combination of (), {} and [].

    Also detects errors like: ([)], )[]() and ()(, ...

    bool isWellFormatted(string line)
    {           
            Stack<char> lastOpen = new Stack<char>();
            foreach (var c in line)
            {               
                switch (c)
                {
                    case ')':
                        if (lastOpen.Count == 0 || lastOpen.Pop() != '(') return false;
                        break;
                    case ']':
                        if (lastOpen.Count == 0 || lastOpen.Pop() != '[' ) return false;
                        break;
                    case '}':
                        if (lastOpen.Count == 0 || lastOpen.Pop() != '{') return false;
                        break;
                    case '(': lastOpen.Push(c); break;
                    case '[': lastOpen.Push(c); break;
                    case '{': lastOpen.Push(c); break;
                }                                                                       
            }
            if (lastOpen.Count == 0) return true;
            else return false;
        }
    
    0 讨论(0)
  • 2020-12-01 09:10
    import java.util.Stack;
    
    public class CheckBalancedParenthesis {
    
        public static void main (String args[]){
            CheckBalancedParenthesis checker = new CheckBalancedParenthesis();
            System.out.println(checker.checkBalancedParenthesis("{}}{}{}{}{}"));
        }
    
        public boolean checkBalancedParenthesis(String pattern){
            Stack stack = new Stack();
            for(int i = 0; i < pattern.length();i++){
                char c = pattern.charAt(i);
                if(c == '{'){
                    stack.push(c);
                }else if (c == '}'){
                    if(!stack.isEmpty()){
                        stack.pop();
                    } else{
                        System.out.println("Error at - " + i);
                        return false;
                    }
                }
            }
            return stack.isEmpty();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 09:11

    I would use a queue and a stack, to check for opening and closing match

            var dictionary = new Dictionary<string, string>() {
                { "{", "}" },
                {"[", "]" },
                {"(",")" }
            };
    
    
            var par = "{()}";
            var queue = new Queue();
            var stack = new Stack();
    
            bool isBalanced = true;
    
            var size = par.ToCharArray().Length;
    
            if(size % 2 != 0)
            {
                isBalanced = false;
            }
            else
            {
                foreach (var c in par.ToCharArray())
                {
                    stack.Push(c.ToString());
                    queue.Enqueue(c.ToString());
                }
    
                while (stack.Count > size/2 && queue.Count > size/2)
                {
                    var a = (string)queue.Dequeue();
                    var b = (string)stack.Pop();
    
                    if (dictionary.ContainsKey(a) && b != dictionary[a])
                    {
                        isBalanced = false;
    
                    }
    
    
                }
    
    
            }
    
            Console.WriteLine(isBalanced?"balanced!":"Not Balanced");
    
            Console.ReadLine();
    

    in the first iteration for example, a ='{' and b ='}' so you do your check whether it is balanced or not

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