2021.01.12 연습

 

  • 사용언어 : java

 


class Solution {
    public boolean isValid(String s) {
        
        Stack<Character> stack = new Stack<Character>();
        
        for (char i : s.toCharArray()) {

            if ( i == '(' || i == '{' || i == '[') {
                stack.push(i);
            } else {
                
                if (stack.isEmpty()) return false;
                
                char check = stack.peek();
                
                if ( i == ')' && check != '(' || i == '}' && check != '{'  || i == ']' && check != '[' ) {
                     return false;
                } else {
                     stack.pop();
                }

            }          
        }
        return stack.isEmpty();
    }
}

Runtime: 1 ms, faster than 98.74% of Java online submissions for Valid Parentheses. Memory Usage: 37.4 MB, less than 33.67% of Java online submissions for Valid Parentheses.

 


  • 다른 코드 참고
class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}