Tag Archives: Java Stack questions

Parentheses / Brackets Check (Hacker Rank Interview Questions)

Match the braces and verify weather all the opening braces has the closing braces in right order.

Input: String of braces only: “[{}]()[{{()}}()]”
Output: Yes

Input: String of braces only: “[{}]({{()}}()]”
Output: No

So the basic approach would be to use stack to verify the correct order of braces.

Iterate over each braces from start to end and do the below step at each iteration.

Step 1.  When you find opening bracket: Do Push.
Step 2.  When you find closing bracket: Do pop and check whether closing and opening bracket match. If yes, then continue, if not then break and return NO.

Below is the Screenshots of the project structure followed by the source code:

You can have below code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git

 

Project Structure in Eclipse:

HackerRankProjectStructure

 

 

Below is the code:

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class BracesCheck {
	
	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		System.out.println("Please Enter Your String");
		String inputString = in.nextLine();
		System.out.println(checkBraces(inputString));
		in.close();
	}
	
	static String checkBraces(String value){
		Stack<Character> specialCharStack = new Stack<Character>();
		String response = "Fail";
	    char tempChar;
	    Character[] openingBraces = {'[','(','{'};
	    Character[] closingBraces = {']',')','}'};
	    List<Character> openingBracesList = Arrays.asList(openingBraces);
	    List<Character> closingBracesList = Arrays.asList(closingBraces);
	   
	    
	    
	    if(value == null){
	    	return response;
	    }else if(value.length()==0){
	    	response = "Pass";
	    }else{
	    
		    for(int i=0; i < value.length(); i++) {
		    	tempChar = value.charAt(i);
		    	
		    	if(openingBracesList.contains(tempChar)){
					specialCharStack.push(tempChar);
				}else if(closingBracesList.contains(tempChar)){
					if(!specialCharStack.isEmpty()){
						if(tempChar==')' && '(' != specialCharStack.pop()){
							return response;
						}else if(tempChar=='}' && '{' !=specialCharStack.pop()){
							return response;
						}else if(tempChar==']' && '[' != specialCharStack.pop()){
							return response;
						}
					}else{
						return response;
					}
				}else{
					return response;
				}
		    }
		    
	    }
		
		if( specialCharStack.isEmpty()){
			response = "Pass";
			return response;
		}else{
			return response;
		}
	}
}

The output of the above code

Please Enter Your String
()
Pass

Please Enter Your String
({({()})})
Pass

Please Enter Your String
(((((((
Fail

Please Enter Your String
)))))(((((
Fail

Please Enter Your String
))))))
Fail


You can have above code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git