-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_valid_parentheses.jl
106 lines (74 loc) · 2.22 KB
/
06_valid_parentheses.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#=
Problem 6: Valid parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
Credits: LeetCode. All rights reserved.
Solution author: Bruno Jacob, UCSB
=#
using BenchmarkTools
function valid_parentheses(s::String)::Bool
"""
valid_parentheses(x::String) -> Bool
Given a string s containing just the following characters:
'(', ')', '{', '}', '[' and ']',
determines if the input string is valid.
Example:
valid_parentheses("()[]{}")
Input: "()[]{}"
Output: True
"""
# Creates Dict bracket map:
# Purpose: maps each bracket type with its closing counterpart
# IMPORTANT: be careful, in Julia, '' are chars, "" are strings
bracket_map = Dict('('=>')', '['=>']', '{'=>'}')
# Creates list of open brackets
open_list = ['(', '[', '{']
# Create an empty stack list
stack = []
# Loop over chars in s:
for i in s # Be careful, char will be of class char, not strings!
# If i is an open bracket, append the char to the stack list
if i in open_list
append!(stack,i)
# Else, check the last element in the stack list to see if its counterpart exists
# (and make sure stack is not empty)
elseif (length(stack)>0)
if i == bracket_map[stack[end]]
# Then pop element out of the stack
pop!(stack)
else
return false
end
# In case char is different than the valid ones, returns false
else
return false
end
end
# If stack is empty, return true; else, false
return isempty(stack)
end
# Example parameter:
#a = valid_parentheses("[[{()[]{}}]]")
#println(a)
# To benchmark:
bm = @benchmark valid_parentheses(s) setup=(s="[[{()[]{}}]]")
display(bm)