Skip to content

Commit 9bd4818

Browse files
authored
Merge pull request #588 from bacecek/bacecek_brackets_in_java
Solve simple balanced brackets task.
2 parents 1102d56 + 58a534a commit 9bd4818

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

brackets/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
## Balanced Brackets
2+
3+
### Description
4+
Given a sequence consisting of brackets, determine whether the expression is balanced. A sequence of brackets is balanced if every open bracket can be paired uniquely with a closed bracket that occurs after the former. Also, the interval between them must be balanced. You will be given three types of brackets: (, {, [.
5+
6+
`([{}])` - this is balanced brackets
7+
8+
`([{]})` - this is not balanced brackets

brackets/java/brackets.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.Stack;
2+
3+
public class brackets {
4+
5+
public static void main(String[] args) {
6+
System.out.println(solve("[{()}[]({[]})]")); // yes
7+
System.out.println(solve("()()")); // yes
8+
System.out.println(solve("((()[]")); // no
9+
}
10+
11+
public static String solve(String s) {
12+
Stack<Character> stack = new Stack<>();
13+
for (char c : s.toCharArray()) {
14+
if (c == '(' || c == '[' || c == '{') stack.push(c);
15+
else {
16+
if (stack.empty()) return "no";
17+
char p = stack.pop();
18+
if (c == ')') {
19+
if (p != '(') return "no";
20+
else continue;
21+
}
22+
if (c == ']') {
23+
if (p != '[') return "no";
24+
else continue;
25+
}
26+
if (c == '}') {
27+
if (p != '{') return "no";
28+
}
29+
}
30+
}
31+
return stack.empty() ? "yes" : "no";
32+
}
33+
34+
}

0 commit comments

Comments
 (0)