|
| 1 | +/* |
| 2 | +
|
| 3 | +The nested brackets problem is a problem that determines if a sequence of |
| 4 | +brackets are properly nested. A sequence of brackets s is considered properly nested |
| 5 | +if any of the following conditions are true: |
| 6 | + - s is empty |
| 7 | + - s has the form (U) or [U] or {U} where U is a properly nested string |
| 8 | + - s has the form VW where V and W are properly nested strings |
| 9 | +For example, the string "()()[()]" is properly nested but "[(()]" is not. |
| 10 | +The function called is_balanced takes as input a string S which is a sequence of brackets and |
| 11 | +returns true if S is nested and false otherwise. |
| 12 | +
|
| 13 | + author: akshay sharma |
| 14 | + date: 2017-10-17 |
| 15 | +*/ |
| 16 | +import java.util.Scanner; |
| 17 | +import java.util.Stack; |
| 18 | +import java.util.ArrayList; |
| 19 | + |
| 20 | +class nested_brackets { |
| 21 | + |
| 22 | + static boolean is_balanced(char[] S) { |
| 23 | + Stack<Character> stack = new Stack<>(); |
| 24 | + String pair = ""; |
| 25 | + for (int i = 0; i < S.length; ++i) { |
| 26 | + if (S[i] == '(' || S[i] == '{' || S[i] == '[') { |
| 27 | + stack.push(S[i]); |
| 28 | + } else if (stack.size() > 0) { |
| 29 | +// pair = (stack.lastElement() + S[i]); |
| 30 | + if (!pair.equals("[]") && !pair.equals("()") && !pair.equals("{}")) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + } else { |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return stack.isEmpty(); |
| 39 | + } |
| 40 | + |
| 41 | + static void print(Object a) { |
| 42 | + System.out.println(a); |
| 43 | + } |
| 44 | + |
| 45 | + public static void main(String args[]) { |
| 46 | + try { |
| 47 | + Scanner in = new Scanner(System.in); |
| 48 | + print("Enter sequence of brackets: "); |
| 49 | + String S = in.nextLine(); |
| 50 | + if (is_balanced(S.toCharArray())) { |
| 51 | + print(S + " is balanced"); |
| 52 | + } else { |
| 53 | + print(S + " ain't balanced"); |
| 54 | + } |
| 55 | + in.close(); |
| 56 | + } catch (Exception e) { |
| 57 | + e.toString(); |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments