Skip to content

Commit

Permalink
balanced bracket
Browse files Browse the repository at this point in the history
  • Loading branch information
brendonmiranda committed Oct 31, 2024
1 parent 31c20c6 commit a41c8c3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/main/java/data/structure/stack/Brackets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package data.structure.stack;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
* Check if string is a balanced bracket or not. e.g (([{}])) is balanced, (([{])) it is not.
* That's a stack data structure solution o(n)
*/
public class Brackets {


public boolean balancedBracket(String s) {

// ([])
Map<Character, Character> openClosedKeyValue = new HashMap<>();
openClosedKeyValue.put('(', ')');
openClosedKeyValue.put('{', '}');
openClosedKeyValue.put('[', ']');

Stack<Character> stack = new Stack<>();
var stringArr = s.toCharArray();
for (char c : stringArr) {

if (openClosedKeyValue.containsKey(c)) { // open

stack.push(c);
} else { // closed

var lastOpenedBracket = stack.pop();
if (!openClosedKeyValue.get(lastOpenedBracket).equals(c)) // if char is not corresponding to the closed bracket of the last opened bracket
return false;

}
}

return stack.isEmpty();
}

}
17 changes: 17 additions & 0 deletions src/test/java/data/structure/stack/BracketsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package data.structure.stack;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class BracketsTest {

@Test
public void test() {
Brackets brackets = new Brackets();
Assertions.assertTrue(brackets.balancedBracket("(([{}]))"));
Assertions.assertFalse(brackets.balancedBracket("(([{]))"));
Assertions.assertFalse(brackets.balancedBracket("(([{}]{)"));

}

}

0 comments on commit a41c8c3

Please sign in to comment.