Match the braces and verify whether 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 a stack to verify the correct order of braces.
Iterate over each brace 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.
https://github.com/Niravkumar-Patel/SnippetExampleRepo.git
Project Structure in Eclipse:
Below is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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.