32. Longest Valid Parentheses
This commit is contained in:
@@ -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>
|
||||
5
32. Longest Valid Parentheses/Program.cs
Normal file
5
32. Longest Valid Parentheses/Program.cs
Normal file
@@ -0,0 +1,5 @@
|
||||
var sol = new Solution();
|
||||
|
||||
// System.Console.WriteLine(sol.LongestValidParentheses(")()())"));
|
||||
// System.Console.WriteLine(sol.LongestValidParentheses("()(()"));
|
||||
System.Console.WriteLine(sol.LongestValidParentheses("()(())"));
|
||||
43
32. Longest Valid Parentheses/Solution.cs
Normal file
43
32. Longest Valid Parentheses/Solution.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user