fork(2) download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Stack;
  4.  
  5. /**
  6.  * Given an sequence of brackets , confirm if sequence is valid
  7.  * @author PRATEEK
  8.  */
  9. class ValidateBrackets {
  10.  
  11. private static Map<Character,Character> hash = new HashMap<>();
  12.  
  13. static {
  14. hash.put('{','}');
  15. hash.put('[',']');
  16. hash.put('(',')');
  17. }
  18.  
  19. /**
  20. * Sub-routine to validate the sequence of brackets
  21. * @param s
  22. * @return
  23. */
  24. public static boolean validate(String s){
  25. char[] arr = s.toCharArray();
  26.  
  27. Stack<Character> stack = new Stack<>();
  28. for(Character c:arr)
  29. {
  30. switch (c) {
  31. case '[':
  32. case '{':
  33. case '(':
  34. stack.push(c);
  35. break;
  36.  
  37. case ']':
  38. case '}':
  39. case ')':
  40. {
  41. if(hash.values().contains(c))
  42. {
  43. if(!stack.isEmpty() && hash.get(stack.peek())==c)
  44. stack.pop();
  45. else if(stack.isEmpty())
  46. return false;
  47. }
  48.  
  49. }
  50. break;
  51. default:
  52. break;
  53. }
  54. }
  55. return stack.isEmpty();
  56. }
  57.  
  58. public static void main(String[] args) {
  59. String s= "{()}[]";
  60. boolean isValid = validate(s);
  61. System.out.println("input: "+s);
  62. System.out.println("output: " +isValid);
  63. }
  64. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
input: {()}[]
output: true