Harry You
Harry You

Reputation: 87

Trying to get the code to check if there are even brackets

I am currently trying to come up with a code that will scan a string and check to see if there is an even number of open and closing brackets on each line. If so, it would return true. (Excuse me for the incorrectness in formatting but I could not get the examples to properly take shape unless I identified it as code)

{}    // The code would return true    
{{}}
{}{}
{{{}{{}}}}


}     // The code would return false
{}
}}{
{{{}{}

What I tried so far:

    public boolean bracketsMatch(String brackets)
{
  int lb = 0;
  int rb = 0;
  int i = 0;
  while (brackets.charAt(i) == '{' || brackets.charAt(i) == '}' || brackets.charAt(i) == '')
  {
      if (brackets.charAt(i) == '{')
      {
        lb += 1; 
      }

      if (brackets.charAt(i) == '}')
      {
          rb += 1;
      }

      if (brackets.charAt(i) == '')
      {
          if (lb / rb == 2)
          {
              // Is it possible to get the code scan the next line to next line?
              // need an extra statement here for ^^ before I can place the if statement below
            if (bracket.charAt(i + 1) == '')
            {
              return true; 
            }
          }

            else 
          {
              return false;
          }
      }
      i++

  }
}

I apologize in advance for any experienced programmers as this would be an inefficient nightmare. I am relatively new to programming in general. I attempted to have the code check for the number of left brackets (lb) and right brackets (rb). Whenever the code came to an empty string, it would divide lb by rb. If the code did not equal 2, the code would return false. I probably have more than a dozen errors in this code, but I was wondering if there was any way to have the code go onto the next line to scan the next set of brackets. Thanks for any help in advance.

EDIT 1:

public boolean bracketsMatch(String brackets)
{
  int balance = 0;
  for (int i = 0; i < brackets.length(); i++)
  {
      char value = brackets.charAt(i);
      if (value == '{')
      {
        balance += 1; 
      }

      else if (value == '}')
      {
          balance -= 1;
      }

  }

  if (balance != 0)
  {
      return false;
  }

  else
  {
      return true;
  }
}

Upvotes: 0

Views: 1004

Answers (2)

Someone
Someone

Reputation: 444

Alternative way to do

You can use Java Stack class [As it represent the List-In-First-Out stack of object].You can use the push and pop method of Stack class. Here is the implementation.

public class BracketMatching {

    public static boolean bracketMatch(String input){

        Stack<Character> st = new Stack<>();
    
        for(char c : input.toCharArray()){
    
            if( c == '{')
                st.push(c);
        
            else if(c == '}'){
            
                if(st.isEmpty())
                    return false;
            
                st.pop();   
            }
        }
    
        if(st.isEmpty())
        return true;

        return false;
    
    }
    public static void main(String[] args){
    
        String input1 = "{}{{}}{}{}{{{}{{}}}}";
        String input2 = "}{}}}{{{{}{}";
    
        System.out.println(bracketMatch(input1));
        System.out.println(bracketMatch(input2));
    
    }
}

Upvotes: 1

janos
janos

Reputation: 124724

This won't compile, as '' is an invalid character literal:

if (brackets.charAt(i + 1) == '')

And your current approach of counting opening and closing brackets, and checking the value of lb / rb won't yield the right result.

You don't need to count the right brackets. You only need to count the open brackets, and reduce that count as they get closed.

Here's a sketch of an algorithm you can use, I hope to not spoil the exercise:

  1. For each character in the string
  2. If it's an open bracket, increment the count
  3. If it's a close bracket
    • If the open count is 0, there's nothing to close, so they are not balanced, we can stop
    • Decrement the count
  4. After all characters, if the open count is 0, the brackets are balanced

As an additional code review note, this is bad in many ways:

  if (brackets.charAt(i) == '{') {
    // ...
  }

  if (brackets.charAt(i) == '}') {
    // ...
  }

What's bad:

  • Calling brackets.charAt(i) repeatedly is unnecessary if the result will always be the same. Call it once and save the result in a variable.
  • The two if conditions are exclusive: if the first is true, the second won't be true, so it's pointless to evaluate it. The second condition should be if else instead of if. And instead of an if-else chain, a switch could be more interesting here.
  • Instead of calling the string brackets, it would be better to call it something more general. What if the actual input is "{something}"? Then it contains more than just brackets, but the algorithm would work just the same. Calling it brackets is misleading.

Upvotes: 3

Related Questions