parent
6007c0dd33
commit
e357d81606
@ -0,0 +1,36 @@
|
||||
20. Valid Parentheses
|
||||
Easy
|
||||
|
||||
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
|
||||
|
||||
An input string is valid if:
|
||||
|
||||
Open brackets must be closed by the same type of brackets.
|
||||
Open brackets must be closed in the correct order.
|
||||
Every close bracket has a corresponding open bracket of the same type.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: s = "()"
|
||||
Output: true
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: s = "()[]{}"
|
||||
Output: true
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: s = "(]"
|
||||
Output: false
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
1 <= s.length <= 104
|
||||
s consists of parentheses only '()[]{}'.
|
||||
|
||||
|
@ -0,0 +1,66 @@
|
||||
package validparens
|
||||
|
||||
type stack struct {
|
||||
store []rune
|
||||
}
|
||||
|
||||
func (s *stack) Push(r rune) {
|
||||
s.store = append(s.store, r)
|
||||
}
|
||||
|
||||
func (s *stack) Pop() rune {
|
||||
res := s.store[len(s.store)-1]
|
||||
s.store = s.store[:len(s.store)-1]
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *stack) Length() int {
|
||||
return len(s.store)
|
||||
}
|
||||
|
||||
func (s *stack) OnTop(r rune) bool {
|
||||
if s.Length() == 0 {
|
||||
return false
|
||||
}
|
||||
return s.store[len(s.store)-1] == r
|
||||
}
|
||||
|
||||
func NewStack() stack {
|
||||
store := make([]rune, 0)
|
||||
return stack{
|
||||
store: store,
|
||||
}
|
||||
}
|
||||
|
||||
func isValid(s string) bool {
|
||||
history := NewStack()
|
||||
|
||||
for _, r := range s {
|
||||
switch r {
|
||||
case '{', '[', '(':
|
||||
history.Push(r)
|
||||
case ')':
|
||||
if !history.OnTop('(') {
|
||||
return false
|
||||
}
|
||||
history.Pop()
|
||||
case ']':
|
||||
if !history.OnTop('[') {
|
||||
return false
|
||||
}
|
||||
history.Pop()
|
||||
case '}':
|
||||
if !history.OnTop('{') {
|
||||
return false
|
||||
}
|
||||
history.Pop()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return history.Length() == 0
|
||||
}
|
||||
|
||||
func IsValid(s string) bool {
|
||||
return isValid(s)
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package validparens_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.jxs.me/leetgo/validparens"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestExamples(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"": true,
|
||||
"(": false,
|
||||
"()": true,
|
||||
"[{()}]": true,
|
||||
"[(])": false,
|
||||
}
|
||||
|
||||
for input, expected := range cases {
|
||||
require.Equal(t, expected, validparens.IsValid(input))
|
||||
}
|
||||
}
|
Loading…
Reference in new issue