Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!