Skip to content

Commit 6b8c173

Browse files
Denis BuzmakovDenis Buzmakov
authored andcommitted
added solution for task with brackets
1 parent b43828b commit 6b8c173

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

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)