Press "Enter" to skip to content

Posts tagged as “parentheses”

花花酱 LeetCode 921. Minimum Add to Make Parentheses Valid

Given a stringĀ SĀ ofĀ '('Ā andĀ ')'Ā parentheses, we add the minimum number of parentheses (Ā '('Ā orĀ ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or
  • It can be written asĀ ABĀ (AĀ concatenated withĀ B), whereĀ AĀ andĀ BĀ are valid strings, or
  • It can be written asĀ (A), whereĀ AĀ is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

 

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

Note:

  1. S.length <= 1000
  2. SĀ only consists ofĀ '('Ā andĀ ')'Ā characters.

Solution: Counting

Time complexity: O(n)

Space complexity: O(1)

C++

花花酱 LeetCode 20. Valid Parentheses

Problem

Given a string containing just the charactersĀ '(',Ā ')',Ā '{',Ā '}',Ā '['Ā andĀ ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string isĀ also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Solution: Stack

Using a stack to track the existing open parentheses, if the current one is a closeĀ parenthesis but does not match the top of the stack, return false, otherwise pop the stack. Check whether the stack is empty in the end.

Time complexity: O(n)

Space complexity: O(n)

C++

Python3

Related Problems