Balanced parentheses:
#1: Java example program to check given string has valid parenthesis or not.
Output:
- A string which contains below characters in correct order.
- "{}" "[]" "()"
- We need to check whether given string has valid order of parenthesis order.
- If the parenthesis characters are placed in order then we can say its valid parentheses or balanced parentheses.
- If the parentheses characters are not in correct order or open and close then we can say it is not balanced or invalid parenthesis.
- Program to check given string has a valid parenthesis or not.
- package instanceofjava;
- import java.util.Stack;
- public class BalancedParenthensies {
- public static void main(String[] args) {
- System.out.println(checkParenthensies("{(xxx,yyy)}"));
- System.out.println(checkParenthensies("{)(acd,bcvfs}"));
- System.out.println(checkParenthensies("{(xxx},yyy)"));
- System.out.println(checkParenthensies("[(xxx),yyy]"));
- }
- public static boolean checkParenthensies(String str) {
- Stack<Character> object = new Stack<Character>();
- for(int i = 0; i < str.length(); i++) {
- char ch = str.charAt(i);
- if(ch == '[' || ch == '(' || ch == '{' ) {
- object.push(ch);
- } else if(ch == ']') {
- if(object.isEmpty() || object.pop() != '[') {
- return false;
- }
- } else if(ch == ')') {
- if(object.isEmpty() || object.pop() != '(') {
- return false;
- }
- } else if(ch == '}') {
- if(object.isEmpty() || object.pop() != '{') {
- return false;
- }
- }
- }
- return object.isEmpty();
- }
- }
Output:
- true
- false
- false
- true
No comments