kotlin-coding-challenges

Valid parentheses

Instructions

Given a string containing only the characters (, ), {, }, [ and ], implement a function to determine if the input string is valid. An input string is valid if:

Challenge Solution

Examples

isValidParentheses("()") // true

isValidParentheses("()[]{}") // true

isValidParentheses("(]") // false - '(' must be closed by ')' not ']'

isValidParentheses("([)]") // false - brackets are interleaved, not closed in correct order

isValidParentheses("{[]}") // true - properly nested brackets

Hints

Hint 1 Use a stack.
Hint 2 Push open brackets to the stack. For each close bracket pop the stack and check that popped bracket matches.