Decode Algorithms & LeetCode
  • Decode Algorithms & LeetCode
  • G家练习
  • Array
    • Two Sum
    • Two Pointers
    • PrefixSum
    • Matrix
    • Interval & Sweepline
    • Sort
    • Iterator
    • Segment Tree
  • Binary Search
    • 教学
    • Binary Search on Matrix
    • Binary Search To Find An Answer
  • String
    • Parenthesis
    • Sliding Window
    • Trie
  • LinkedList
  • Tree
    • Level Order Traversal
    • BST or Inorder
    • Construst Tree
  • Stack
  • Heap
  • Greedy
  • BFS
  • DFS
    • DFS on String
    • Backtracking
    • DFS+Memo
  • Graph
    • Union Find
    • Topological Sort
    • Dijkstra
    • Bipartite Graph
  • Dynamic Programing
    • DP on String
    • Knapsack Problem
  • Design
    • Concurrency
  • Math
  • Bit Manipulation
Powered by GitBook
On this page

Was this helpful?

  1. String

Parenthesis

PreviousStringNextSliding Window

Last updated 4 years ago

Was this helpful?

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    char[] chars = s.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] == '(') stack.push(')');
        else if (chars[i] == '{') stack.push('}');
        else if (chars[i] == '[') stack.push(']');
        else {
            if (stack.isEmpty() || stack.pop() != chars[i]) return false;
        }
    }
    return stack.isEmpty();
}

def minAddToMakeValid(self, S: str) -> int:
    stack = []
    res = 0
    for c in S:
        if c == '(':
            stack.append(c)
        elif c == ')':
            if not stack:
                res += 1
            else:
                stack.pop()
    res += len(stack)
    return res
public String minRemoveToMakeValid(String s) {
    Stack<Integer> stack = new Stack<>();
    Set<Integer> indexToRemove = new HashSet<>();
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') stack.push(i);
        else if (s.charAt(i) == ')') {
            if (stack.isEmpty()) {
                indexToRemove.add(i);
            } else stack.pop();
        }
    }
    while (!stack.isEmpty()) indexToRemove.add(stack.pop());
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (!indexToRemove.contains(i)) sb.append(s.charAt(i));
    }
    return sb.toString();
}

20. Valid Parentheses
921. Minimum Add to Make Parentheses Valid
1249. Minimum Remove to Make Valid Parentheses