-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
31c20c6
commit a41c8c3
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("(([{}]{)")); | ||
|
||
} | ||
|
||
} |