Try using str.charAt(i) in a for-loop. This method returns one by one each char of the String. Then you can count the different brackets that open and close and make sure that each time the bracket count must be positive or zero. At the end of the loop all bracket counts must be zero. You must also check that you don't have a case such as this which is wrong :
{ [ } ]
public static boolean isValid(String str) {
//code here
}
javaAddict
Nearly a Senior Poster
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
Obviously the point of your homework is for YOU to come up with a solution. Handing you the solution defeats the purpose. Post your code and describe what troubles you are having if you would like assistance.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
Let's see what you've tried. Easiest method would be to just use regular expressions.
The method javaAddict describes is very simple. When you encounter an opening bracket, increment your bracket counter. When you encounter a closing bracket, decrement the counter. If the counter is 0 at the end of the FOR loop, then the equation should be valid.
Phaelax
Practically a Posting Shark
858 posts since Mar 2004
Reputation Points: 92
Solved Threads: 51
Stacks are useful for such things as well.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
In case you have something like this: { [ } ], perhaps you should have some boolean variables for the different brackets(isCloded, isOpened) so you can check that you cannot close something if you are inside a different unclosed bracket. Try to remember the most recent open bracket
javaAddict
Nearly a Senior Poster
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
Or you could just use an abstract data structure, such as a stack which is ideal for this, like Ezzaral suggested in post #6
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439