-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatching_brackets.sh
More file actions
66 lines (51 loc) · 1.04 KB
/
Copy pathmatching_brackets.sh
File metadata and controls
66 lines (51 loc) · 1.04 KB
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
#!/usr/bin/env bash
set -o errexit
set -o nounset
bracket_stack=""
declare -A matching_brackets=(
["]"]="["
[")"]="("
["}"]="{"
)
function main {
if (( $# != 1 )); then
echo "Usage: $0 <expression-with-brackets>"
exit 1
fi
sequence="$1"
for (( i=0; i<${#sequence}; i++ )); do
char="${sequence:$i:1}"
handleChar "${char}"
done
if [[ "${bracket_stack}" != "" ]]; then
reportFalse
fi
echo "true"
}
function handleChar {
char=$1
case "${char}" in
'[' | '(' | '{')
pushStack "${char}"
;;
']' | ')' | '}')
popStackAndValidate "${matching_brackets[${char}]}"
;;
esac
}
function pushStack {
char=$1
bracket_stack="${char}${bracket_stack}"
}
function popStackAndValidate {
char=$1
if [[ "${bracket_stack}" == "" ]] || [[ "${bracket_stack}" != "${char}"* ]]; then
reportFalse
fi
bracket_stack=${bracket_stack#?}
}
function reportFalse {
echo "false"
exit 0
}
main "$@"