diff --git a/validparens/readme.md b/validparens/readme.md new file mode 100644 index 0000000..15e8e60 --- /dev/null +++ b/validparens/readme.md @@ -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 '()[]{}'. + + diff --git a/validparens/validparens.go b/validparens/validparens.go new file mode 100644 index 0000000..551ed0d --- /dev/null +++ b/validparens/validparens.go @@ -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) +} diff --git a/validparens/validparens_test.go b/validparens/validparens_test.go new file mode 100644 index 0000000..e7fbe47 --- /dev/null +++ b/validparens/validparens_test.go @@ -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)) + } +}