27 Apr 2014

Validate Brackets

Problem Statement:
    Given a sequence of brackets, validate if the sequence is valid.

Solution:
Run Source Code

We all must have solved this problem during college as common application of stack for solving mathematical expressions. Below is the implementation to validate given sequence of brackets.

 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.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * Given an sequence of brackets , confirm if sequence is valid
 * @author PRATEEK
 */
public class ValidateBrackets {
 
 private static Map<Character,Character> hash = new HashMap<>();
 
 static {
  hash.put('{','}');
  hash.put('[',']');
  hash.put('(',')');
 }
 
 /**
  * Sub-routine to validate the sequence of brackets
  * @param s
  * @return
  */
 public static boolean validate(String s){
  char[] arr = s.toCharArray();
  
  Stack<Character> stack = new Stack<>();
  for(Character c:arr)
  {
     switch (c) {
   case '[':
   case '{':
   case '(':
    stack.push(c);
    break;
    
   case ']':
   case '}':
   case ')':
   {
    if(hash.values().contains(c))
    {
     if(!stack.isEmpty() && hash.get(stack.peek())==c)
      stack.pop();
     else if(stack.isEmpty())
      return false;
    }
    
   }
    break;
   default:
    break;
   }
  }
  return stack.isEmpty();
 }
 
 public static void main(String[] args) {
  String s= "{()}[]";
  boolean isValid = validate(s);
  System.out.println("input: "+s);
  System.out.println("output: " +isValid);
 }
}

Download Source Code
Please comment and post your suggestions.
Happy Coding !! :)

No comments:

Post a Comment