-3

I'm trying to figure out how to check if a String is formatted correctly with parens: ( and ). There should be the same number of ( as ). Also, the parens should be formatted correctly so that a ( and ) form a pair. Other characters may appear in the String.

Examples:

"()()()()()()()"   // Valid
"((a)(b)((cd)e))"  // Valid
"((d()mk()))()"    // Valid
"((d()mk())))("    // Invalid, the last two parens don't form a pair.
")()"              // Invalid, not equal number of paren types

So, I figured the first step is to check if there are the same number of ( as ) in the String (I found this page to help with that Brackets in String).

I don't know how to approach the part to check if the String is formatted correctly.

Could you guys give me a hint?

EDIT:

My solution is:

import java.util.*; 

public class BracketProblem {

    public boolean checkBrackets(String str) {
        Stack st = new Stack();

        for(int i = 0; i < str.length(); i++){
            char x = str.charAt(i);
            if (x == '(')
                st.push(x);

            if (!st.empty()){
                if (x == ')') 
                    st.pop();
            }
        }

        if(!st.empty()) 
            return false;
        else {
            return true;
        }
    }

    public static void main(String[] args){
        String str = args[0];       
        BracketProblem bp = new BracketProblem();
        System.out.println(bp.checkBrackets(str));
    }
}
Community
  • 1
  • 1
  • 2
    Use a stack - when you read a `(` add it onto the stack, when you read a `)` pop a `(` off of the stack. If you don't get any errors and have an empty stack at the end it's good. – Andrew_CS Jul 15 '14 at 21:27
  • 2
    @Andrew_CS You may want to add that as an answer... – Sinkingpoint Jul 15 '14 at 21:28
  • 1
    If you are taking an abstract data types class (or not) I would do as Andrew suggests and use a stack. Learn a little about them, http://en.wikipedia.org/wiki/Stack_(abstract_data_type). Java Stack: http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html – Hanlet Escaño Jul 15 '14 at 21:32
  • 1
    Question is edited to be more clear on what the OP wants - shouldn't be on hold anymore. – Andrew_CS Jul 16 '14 at 11:42

3 Answers3

4

Grab a piece of paper, write down your string on it with a pencil (pen will do), and then do the checking yourself, while keeping track of your progress on the paper.

Now try to formulate what you're doing in Java.

Update: Sorry if this sounds rude and unhelpful at first but the ability to work things out for yourself is far more important than any algorithm.

biziclop
  • 48,926
  • 12
  • 77
  • 104
  • 2
    Hi biziclop,I don't think your reply is rude, but I was doing the same thing you wrote: I tried to solve the problem on paper first, I just got stuck... – user3831988 Jul 16 '14 at 11:09
3

Use a stack - Read over the char in the String. Push ( as you read them. Pop ( as you read ).

Things to watch out for:

  • If you read an ) and there is not a ( on top of the stack then that's an error.
  • If you get to the end of the String and the stack isn't empty then that's an error.
  • If you get to the end of the String and the stack is empty then it's a valid String.

Here is a link that explains the Stack Concept.

Note: For your purposes you can ignore the other char in the String.

Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
  • Thanks Andrew_CS, I will try this solution now! – user3831988 Jul 16 '14 at 11:09
  • 1
    @user3831988 I hope this approach works for you - Stack is a data structure that you should get familiar with regardless since it helps with many other problems that you'll face in the future. Don't forget to accept an answer if your original question has been answered. Happy programming! – Andrew_CS Jul 16 '14 at 13:04
  • Hi Andrew_CS, thank you very much for your help, I solved the problem with the stack! Also, thanks for making my problem clear! – user3831988 Jul 16 '14 at 13:43
  • no need to use additional memory – Display Name Jul 16 '14 at 14:14
  • @SargeBorsch Why the downvote? If your comment about memory is referring to the use of a stack - a stack is a good choice since the functionality can easily be extended if other chars are required such as { } [ ]. Also, it's good practice for the OP to learn about the data structure. – Andrew_CS Jul 16 '14 at 14:20
  • @Andrew_CS Sarge is correct, however, the OP did not mention any constraints so I do think that this is a decent way of going about things and thus no downvote from me. – Ricky Mutschlechner Jul 18 '14 at 03:06
2

Make a counter variable; increment it upon seeing ( and decrement it upon seeing ). If your counter variable is not 0 at the end, you have an uneven number of parentheses.

However, as ajb suggested in the comments, make sure that the counter variable never goes negative, as this would mean a case such as )( (which is an even number of parentheses, but technically not matching).

Community
  • 1
  • 1
Ricky Mutschlechner
  • 4,291
  • 2
  • 31
  • 36
  • 5
    Also make sure the counter never goes negative. You want to be able to catch `")("`. – ajb Jul 15 '14 at 21:29