Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to Make Brackets Match

Tags:

java

methods

I am trying to do a practice problem where I have to write a method that takes a string of curly brackets and returns true if the brackets match up and false if they don’t. If I'm passed the empty string, it needs to return true. We can also assume that the given string can have { and } in it or be empty.

Matching has to be in the correct order of pairs like "{}" not "}{"
These are examples of brackets matching:
{}
{}{}
{{}}
{{{}{{}}}}

These are examples of the brackets not matching:
{
}{
{{}
{{}}}{}

This is what I currently have (Keep in mind I'm relatively new to coding):

public boolean bracketsMatch(String brackets)
{
    int count = 0;
    if (brackets.length() % 2 == 1){
        return false;
    }
    for(int i = 0; i < brackets.length(); i++){
        if ((brackets.charAt(i)+"") == "{"){
            count++;
        } else if ((brackets.charAt(i)+"") == "}"){
            count--;
        }
        if (count == -1){
            return false;
        }
    }
return count == 0;
}

Inputs like this }{ and {}}{}{ this still dont return the right output.

like image 739
Ryan Circelli Avatar asked May 13 '26 07:05

Ryan Circelli


1 Answers

Your logic works, but the way you're comparing characters is wrong: never use == to compare string values - it tests for reference equality (whether they are the same object). Try brackets.charAt(i) == '{' instead.

like image 139
Kirill Simonov Avatar answered May 14 '26 22:05

Kirill Simonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!