eolymp
bolt
Try our new interface for solving problems
Problems

Sequence of brackets

published at 9/30/15, 2:28:28 pm

Тесты совсем от другой задачи что ль?

published at 3/14/19, 1:21:59 am

Во всяком случае сейчас с тестами все в порядке

published at 11/24/23, 8:11:26 am

{({)}} try this one too if you wanna find out why your program is wrong

published at 4/3/24, 2:17:25 am

import java.util.*;

public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);

    // Read the input string
    String sequence = scanner.nextLine();

    // Check if the sequence is correct
    String result = isCorrectSequence(sequence) ? "yes" : "no";

    // Print the result
    System.out.println(result);
}

public static boolean isCorrectSequence(String sequence) {
    Stack<Character> stack = new Stack<>();

    // Iterate through each character in the sequence
    for (char c : sequence.toCharArray()) {
        if (c == '(' || c == '[' || c == '{') {
            // Push opening brackets onto the stack
            stack.push(c);
        } else if (c == ')' || c == ']' || c == '}') {
            // Check for matching closing brackets
            if (stack.isEmpty()) {
                return false; // Unmatched closing bracket
            }

            char top = stack.pop();

            // Check if the top of the stack matches the current closing bracket
            if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}' && top != '{')) {
                return false; // Mismatched brackets
            }
        }
    }

    // If the stack is empty, all brackets were matched
    return stack.isEmpty();
}

}