Skip to content

Commit

Permalink
Create valid-brace.md
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen authored Jan 24, 2024
1 parent b4bb55a commit 490415c
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions items/valid-brace.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
rank: 1
link: https://leetcode.cn/problems/valid-parentheses/submissions/498038213/
description: 有效的括号
---

```golang
func isValid(s string) bool {
if len(s) % 2 != 0 {
return false
}

braceMap := map[rune]rune{
'(': ')',
'{': '}',
'[': ']',
}

for len(s) > 0 {
var leftIndex int
var leftBrace rune

var a, b, c int
for i, cc := range s {
if cc == '(' {
a += 1
leftIndex = i
leftBrace = cc
} else if cc == ')' {
a += -1
} else if cc == '{' {
b += 1
leftIndex = i
leftBrace = cc
} else if cc == '}' {
b += -1
} else if cc == '[' {
c += 1
leftIndex = i
leftBrace = cc
} else if cc == ']' {
c += -1
}
}
if !(a == 0 && b == 0 && c == 0) {
return false
}

if len(s) == leftIndex + 1 {
// left brace in the last char
return false
}
if braceMap[leftBrace] != rune(s[leftIndex + 1]) {
return false
}

if len(s) == 2 {
break
}
s = s[0:leftIndex] + s[leftIndex+2:]
}
return true
}
```

0 comments on commit 490415c

Please sign in to comment.