How to validate the Parentheses are opening and closing in correct order
To validate the correct order of the parentheses the sequence of characters is required to be analyzed in a string value:
- First define all types of parentheses which needs to be validated in the input string like ( , ) , { , } , [, ]
- Maintain the input order of the predefined parenthesis types.
- Before closing a parentheses validate the opening status of same type of parentheses.
The below Java program helps us to validate the correct order parentheses
package com.errorConsole.string.validation;
import java.util.HashMap;
import java.util.Stack;
public class ParenthesesValidator {
public static void main(String arg[]) {
//Valid Parentheses String value
String inputString = "loading [a {file} ] with ( 10 number ) data";
boolean isValidInput = validateParenthesesOrder(inputString);
System.out.println("\nValid Parentheses Order = " + inputString);
System.out.println("\nIs Valid = " + isValidInput);
System.out.println("\n======================================================================================== ");
//Invalid Parentheses String value
inputString = "loading [a {file} with (10 number ] ) data";
isValidInput = validateParenthesesOrder(inputString);
System.out.println("\n\nInvalid Parentheses Order = " + inputString);
System.out.println("\nIs Valid = " + isValidInput);
}
public static boolean validateParenthesesOrder(String inputString) {
//Convert String to character array
char[] charArray = inputString.toCharArray();
//Create map with predefined parentheses types
HashMap<Character, Character> hashMap = new HashMap<Character, Character>();
hashMap.put('(', ')');
hashMap.put('[', ']');
hashMap.put('{', '}');
//Stack to maintain the order
Stack<Character> characterStack = new Stack<Character>();
for (Character c : charArray) {
if (hashMap.keySet().contains(c)) {
characterStack.push(c);
} else if (hashMap.values().contains(c)) {
if (!characterStack.isEmpty() && hashMap.get(characterStack.peek()) == c) {
characterStack.pop();
} else {
return false;
}
}
}
return characterStack.isEmpty();
}
}
The above program produces the below output where invalid parentheses order is marked in red colour