You are viewing a single comment's thread. Return to all comments →
Solution using two stacks :
import java.util.*; class Solution{ public static void main(String[] args) { HashMap<String, String> hMap=new HashMap<>(); hMap.put("{", "}"); hMap.put("}", "{"); hMap.put("(", ")"); hMap.put(")", "("); hMap.put("[", "]"); hMap.put("]", "["); Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String inputLine = sc.next(); String [] input = inputLine.split(""); Stack<String> stack=new Stack<>(); Stack<String> newStack=new Stack<>(); int length = inputLine.length(); boolean casePass=false; if(length%2==0){ for(int i=0; i<length; i++){ stack.push(input[i]); //System.out.println(stack); } for(int i=0; i<length; i++){ ////System.out.println(stack); ////System.out.println(stack.size()); String popElement=stack.pop(); //System.out.println(popElement); if(popElement.contains("}") || popElement.contains(")") || popElement.contains("]")){ newStack.push(popElement); }else{ String popElementPair = hMap.get(popElement); String popElementNewStack = newStack.pop(); if(popElementPair.equals(popElementNewStack)){ casePass=true; }else{ casePass=false; } } } } else{ casePass=false; } //System.out.println("newStack : "+newStack); //System.out.println("newStack size : "+newStack.size()); if(casePass==true && newStack.isEmpty()){ System.out.println("true"); }else{ System.out.println("false"); } } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Java Stack
You are viewing a single comment's thread. Return to all comments →
Solution using two stacks :