Longest Valid Parentheses – Leetcode Python
YTTMP3
Posted on February 8, 2022
LeetCode has a Hard coding Problem in Its' Algorith Section "Longest Valid Parentheses". Today We are going to solve this problem.
Question
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Examples
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 3 * 104
s[i] is '(', or ')'.
Solution to Longest Valid Parentheses
Skeleton Code given in Leetcode is
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
Method violence taken every substring O (N ^ 2), then use the method in question 20 determines whether it is legally O (N), the total time of O (N ^ 3).
Violence Solution traversed for one string O (N), from each character, the total number of the left bracket and a right bracket number, and length of each record satisfies the O (N) when the number of left and right bracket == Numbers in parentheses, if left Number of parentheses <number of right parentheses, continue. The time complexity is O(N²).
Stack local stack process with the longest substring matching simulation, after again traversing, namely matching the rest of the stack is not on the brackets, between which the string position, i.e. to meet the requirements, which take a longest. O(N).
Complete Solution
is given at https://hecodesit.com/longest-valid-parentheses-leetcode-python/
Posted on February 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.