fork download
  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args){
  4. Scanner sc = new Scanner(System.in);
  5. while(sc.hasNext()) {
  6. String s = sc.nextLine();
  7. Stack<Character> stack = new Stack<>();
  8. Stack<Integer> type = new Stack<>();
  9.  
  10. for(int i=0; i<s.length(); i++) {
  11. if(s.charAt(i) == '(' || s.charAt(i) == '[') {
  12. if(s.charAt(i) == '(') {
  13. type.push(1);
  14. stack.push('(');
  15.  
  16. }else if(s.charAt(i) == '[') {
  17. type.push(2);
  18. stack.push('[');
  19.  
  20. }
  21.  
  22.  
  23. }else if(s.charAt(i) == ')' || s.charAt(i) == ']'){
  24. if(stack.isEmpty()) {
  25. System.out.println("no");
  26. break;
  27. }
  28.  
  29. int index = type.peek();
  30.  
  31. if(s.charAt(i) == ')' && index == 2) {
  32. System.out.println("no");
  33. break;
  34. }else if(s.charAt(i) == ']' && index == 1) {
  35. System.out.println("no");
  36. break;
  37. }
  38. else {
  39. stack.pop();
  40. type.pop();
  41. }
  42.  
  43. }
  44. if(i == s.length()-1 && stack.isEmpty()) {
  45. System.out.println("yes");
  46. break;
  47. }else if(i == s.length() -1 && !stack.isEmpty()) {
  48. System.out.println("no");
  49. break;
  50. }
  51. }
  52. }
  53.  
  54. }
  55. }
Success #stdin #stdout 0.14s 35412KB
stdin
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
 .
.
stdout
yes
yes
no
no
no
yes
yes
yes