Skip to content

Instantly share code, notes, and snippets.

@turbod
Created October 7, 2023 18:50
Show Gist options
  • Save turbod/9416e55a877db2610633b98d25abe8e0 to your computer and use it in GitHub Desktop.
Save turbod/9416e55a877db2610633b98d25abe8e0 to your computer and use it in GitHub Desktop.

Intuition

Approach

Complexity

  • Time complexity:
  • Space complexity:

Code

VALID_CHARS = {
  '(' => ')',
  '{' => '}',
  '[' => ']',
}

# @param {String} s
# @return {Boolean}
def is_valid(s)
  chars = s.split('')
  return false if chars.size < 2
  openTags = []

  result = chars.all? do |c|
    if VALID_CHARS.keys.include?(c)
      openTags << c
      true
    else
      res = VALID_CHARS[openTags.last] == c
      openTags.pop if res
      res
    end
  end

  result && openTags.empty?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment