-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b4bb55a
commit 490415c
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
``` |