Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
Sorting with single stack and switch arguments in java

I am trying to write 2 methods that can sort a string of brackets using only 1 stack and 1 switch statement. I can't get it to work, I am wondering if it may be because of cases of ' ' in strings? should not default case pick up these or have I understood switch statements wrong? This is where I am right now.

out.println(checkParentheses("({} [()] ({}))"));  // should print true 
                                                                
out.println(!checkParentheses("({} [() ({)})"));  // should print false 


Boolean checkParentheses(String brackets) {

    Deque<Character> stack = new ArrayDeque<>();


    for( char ch : brackets.toCharArray()) {
        if (stack.peek() == matching(ch)) {
            stack.pop();
        } else {
           stack.add(ch);
        }
    }
    return stack.isEmpty();
}


char matching(char ch) {
    // char c = (' ');
    switch (ch) {
        case ')':
            return '(';  // c = '('
        case ']':
            return '[';
        case '}':
            return '{';
        default:
          // return c;
          throw new IllegalArgumentException("No match found");
    }
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  1. Non-bracket characters should be ignored in the input, optionally the input may be cleaned out of them or just skipped quietly
  2. Special checks for opening/closing brackets need to be implemented.

Basically, checkParentheses should be as simple as follows:

public static boolean checkParentheses(String str) {
    if (null == str || str.isEmpty()) {
        return true;
    }
    Deque<Character> stack = new ArrayDeque<>();
    
    for (char c : str.toCharArray()) {
        if (openingBracket(c)) {
            stack.push(c);
        } else if (closingBracket(c)) {
            if (stack.isEmpty() || matchingBracket(c) != stack.pop()) {
                return false;
            }
        } // else ignore non-bracket char quietly
    }
    return stack.isEmpty();
}

Then additional methods may look as follows using switch statement:

static boolean openingBracket(char c) {
    switch (c) {
        case '(': case '[': case '{': case '<':
            return true;
        default:
            return false;
    }
}

static boolean closingBracket(char c) {
    switch (c) {
        case ')': case ']': case '}': case '>':
            return true;
        default:
            return false;
    }
}

static char matchingBracket(char c) {
    switch (c) {
        case ')': return '(';
        case ']': return '[';
        case '}': return '{';
        case '>': return '<';
        default:
            throw new IllegalArgumentException("Bad character found instead of closing bracket: " + c);
    }
}

Then the output of the tests is as follows:

System.out.println(checkParentheses("({} [()] ({}))"));  // true, balance ok
                                                                
System.out.println(!checkParentheses("({} [() ({)})"));  // true, NOT balanced 
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda