Leetcode Note: Go - Maximum Nesting Depth of the Parentheses
Maximum Nesting Depth of the Parentheses - LeetCode
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/
- Go 言語で取り組んだメモ
回答
Go Clean Solution with Stack Implementation Using Linked List (Beats 100% at runtime, 92% at memory) - Maximum Nesting Depth of the Parentheses - LeetCode
https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/solutions/2862308/go-clean-solution-with-stack-implementation-using-linked-list-beats-100-at-runtime-92-at-memory/
type StackNode struct {
val rune
next *StackNode
}
type Stack struct {
length int
top *StackNode
}
func (s *Stack) Push(val rune) {
defer func() {
s.length++
}()
newNode := &StackNode{val:val}
if s.length == 0 {
s.top = newNode
return
}
newNode.next = s.top
s.top = newNode
}
func (s *Stack) Pop() *StackNode {
if s.length == 0 {
return nil
}
toReturn := s.top
s.top = s.top.next
s.length--
return toReturn
}
func (s *Stack) Top() *StackNode {
return s.top
}
func maxDepth(s string) int {
var stack Stack
curMaxDepth := 0
for _, r := range s {
if stack.length > curMaxDepth {
curMaxDepth = stack.length
}
if r != '(' && r != ')' {
continue
}
top := stack.Top()
switch {
case top == nil:
stack.Push(r)
case top.val == '(' && r == ')':
stack.Pop()
default:
stack.Push(r)
}
}
return curMaxDepth
}