Functional Programming
  • Preface
  • Getting Started
  • Sorting
    • Bubble Sort
    • Merge Sort
    • Insertion Sort
  • Stacks
    • Stack
  • Queues
    • Queue
    • Binary Heap (Priority Queue)
  • Trees
    • Binary Tree (Unbalanced)
    • Prefix Trie
  • Graphs
    • Undirected
    • Directed
    • Edge Weighted
  • Dynamic Programming
    • Knapsack
    • Longest Common Substring
    • Staircase
  • Leetcode/InterviewBit
    • 2 Sum [Easy]
    • Longest Valid Parentheses [Medium-Hard]
    • Kth Smallest Element [Medium]
    • Max Profit [2 variations: 1st Easy 2nd Hard]
    • Pretty Print 2D Matrix [Easy]
    • Max Contiguous Subarray (Kadane's) [Medium (just cause its tricky)]
    • Permutations [Medium]
    • Next Permutation [Medium]
Powered by GitBook
On this page

Was this helpful?

  1. Leetcode/InterviewBit

Longest Valid Parentheses [Medium-Hard]

https://leetcode.com/problems/longest-valid-parentheses/

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
def longestValidParentheses(s: String): Int = {

  s.zipWithIndex
    .foldLeft(0 -> List.empty[(Char, Int)]) {
      case ((max, stack), (c, i)) =>
        stack match {
          case (c1, i1) :: rest if (c1 == '(' && c == ')') =>
            Math.max(
              i - rest.headOption.getOrElse('c' -> -1)._2,
              max
            ) -> rest
          case _ => max -> ((c, i) :: stack)
        }
    }
    ._1

}
Previous2 Sum [Easy]NextKth Smallest Element [Medium]

Last updated 6 years ago

Was this helpful?