Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- import java.util.Arrays;
- import java.util.Stack;
- public class Braces {
- public static void main(String[] args) {
- String input1 = "()[]{}"; //YES
- String input2 = "(}{)[]"; //NO
- isBalanced(input1);
- isBalanced(input2);
- }
- public static void isBalanced(String input) {
- HashMap<Character, Character> matchingBraces = new HashMap<Character, Character>();
- matchingBraces.put('{', '}');
- matchingBraces.put('(', ')');
- matchingBraces.put('[', ']');
- Stack<Character> stack = new Stack<Character>();
- for (int i = 0; i < input.length(); i++) {
- char currentBrace = input.charAt(i);
- if (matchingBraces.get(currentBrace) != null) { //opening brace
- stack.push(currentBrace);
- } else { //closing brace
- if (currentBrace != matchingBraces.get(stack.pop())) {
- System.out.println("NO");
- return;
- }
- }
- }
- if (!stack.empty()) {
- System.out.println("NO");
- return;
- }
- System.out.println("YES");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement