Check for balanced parentheses in java containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, check if the input string is valid and return true if the string is balanced otherwise return false.
There are following step Perform :-
- First, we create the object of character stack.
- Traverse the input string and convert into character from str.charAt() method.
- We check stack is empty and push the character to stack.
- Now we push the current character to stack if it is a starting bracket(‘(‘ or ‘{‘ or ‘[‘).
- We pop the current character from the stack if it is a closing bracket. If the popped character doesn’t match with the starting bracket, brackets are not balanced.
- Once the traversing is finished and there are some starting brackets left in the stack, the brackets are not balanced.
import java.util.Stack;
public class BalancedParanthsisMain {
public static void main(String[] args) {
String str = "{[()]}";
Stack st = new Stack();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (st.empty()) {
st.push(str.charAt(i));
} else if (ch == '{' || ch == '[' || ch == '(') {
st.push(ch);
} else if (ch == '}' && st.peek() == '{') {
st.pop();
} else if (ch == ']' && st.peek() == '[') {
st.pop();
} else if (ch == ')' && st.peek() == '(') {
st.pop();
}
}
if (st.empty()) {
System.out.println("Given input String " + str + " is well formed");
} else {
System.out.println("Given input String " + str + " not well formed");
}
}
}
Output :- Given input String {[()]} is well formed