Solution to matching brackets in Bash
This commit is contained in:
20
bash/matching-brackets/matching_brackets.sh
Normal file
20
bash/matching-brackets/matching_brackets.sh
Normal file
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
input="$1"
|
||||
|
||||
# Remove all characters except brackets, braces, and parentheses
|
||||
cleaned_input=$(echo "$input" | tr -cd '[]{}()')
|
||||
|
||||
# Keep replacing any valid pair of brackets, braces, or parentheses with an empty string
|
||||
while [[ $cleaned_input =~ (\(\)|\{\}|\[\]) ]]; do
|
||||
cleaned_input=${cleaned_input//\(\)/}
|
||||
cleaned_input=${cleaned_input//\{\}/}
|
||||
cleaned_input=${cleaned_input//\[\]/}
|
||||
done
|
||||
|
||||
# If the cleaned string is empty, all pairs are matched and nested correctly
|
||||
if [[ -z $cleaned_input ]]; then
|
||||
echo "true"
|
||||
else
|
||||
echo "false"
|
||||
fi
|
||||
Reference in New Issue
Block a user