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));
}
}