public class Solution { struct Item { public char Sym; public int Count; public char? PrevSym; } public int LongestValidParentheses(string s) { var stack = new Stack(); 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; } }