Ryan Circelli
Ryan Circelli

Reputation: 117

Method to Make Brackets Match

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.

Upvotes: 3

Views: 2198

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8491

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.

Upvotes: 1

Related Questions