Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javatechie;
- import java.util.*;
- public class parenthesisBalance {
- public static Map<String,Integer> buildParenthesisMap(String expression){
- Map<String,Integer> map=new HashMap<>();
- for(String exp:expression.split("")){
- if(map.containsKey(exp)){
- map.put(exp,map.get(exp)+1);
- }else{
- map.put(exp,1);
- }
- }
- return map;
- }
- public static boolean compareParenthesis(String expression){
- Map<String,Integer> parenthesisMap=buildParenthesisMap(expression);
- if(parenthesisMap.containsKey("(") && parenthesisMap.containsKey(")")) {
- if(parenthesisMap.get("(")==parenthesisMap.get(")")){
- return true;
- }
- }
- else if(parenthesisMap.containsKey("{") && parenthesisMap.containsKey("}")) {
- if(parenthesisMap.get("{")==parenthesisMap.get("}")){
- return true;
- }
- }
- else if(parenthesisMap.containsKey("[") && parenthesisMap.containsKey("]")) {
- if(parenthesisMap.get("[")==parenthesisMap.get("]")){
- return true;
- }
- }
- return false;
- }
- public static void main(String[] args) {
- System.out.println("is Valid : "+compareParenthesis("[())]"));
- System.out.println("is Valid : "+compareParenthesis("{[()]}"));
- }
- //Also you can use java 8 below poc
- /* public static Map<String, Long> buildParenthesisMap(String expression) {
- return Arrays.stream(expression.split("")).
- collect(Collectors.groupingBy(key -> key, Collectors.counting()));
- *//*
- Also we can use this
- collect(Collectors.toMap(key -> key, key -> 1, Integer::sum));
- *//*
- }*/
- }
Add Comment
Please, Sign In to add comment