32. Longest Valid Parentheses

This commit is contained in:
2026-03-25 22:56:24 +03:00
parent 8c963d3aa2
commit a8727e17a1
4 changed files with 73 additions and 0 deletions

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>_32._Longest_Valid_Parentheses</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,5 @@
var sol = new Solution();
// System.Console.WriteLine(sol.LongestValidParentheses(")()())"));
// System.Console.WriteLine(sol.LongestValidParentheses("()(()"));
System.Console.WriteLine(sol.LongestValidParentheses("()(())"));

View File

@@ -0,0 +1,43 @@
public class Solution
{
struct Item
{
public char Sym;
public int Count;
public char? PrevSym;
}
public int LongestValidParentheses(string s)
{
var stack = new Stack<Item>();
var answer = 0;
foreach (var ch in s)
{
if (stack.Count > 0 && (stack.Peek().Sym == '(' || stack.Peek().PrevSym == '(') && ch == ')')
{
var prev = stack.Pop();
var count = 2;
if (prev.Sym == '#')
{
stack.Pop();
count += prev.Count;
}
while (stack.Count > 0 && stack.Peek().Sym == '#')
count += stack.Pop().Count;
char? prevSym = null;
if (stack.Count > 0)
prevSym = stack.Peek().Sym;
stack.Push(new Item() { Sym = '#', Count = count, PrevSym = prevSym });
answer = Math.Max(answer, count);
}
else
{
stack.Push(new Item() { Sym = ch, Count = 0 });
}
}
return answer;
}
}