Skip to content

Instantly share code, notes, and snippets.

@ymer
Created January 2, 2017 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymer/5c8d3ccd258cafefaaef603713f486e1 to your computer and use it in GitHub Desktop.
Save ymer/5c8d3ccd258cafefaaef603713f486e1 to your computer and use it in GitHub Desktop.
using Combinatorics
function find_matching_pairs(s)
l, starts = [], []
for i in 1:length(s)
if s[i] == "("
push!(starts, i)
elseif s[i] == ")"
push!(l, (pop!(starts), i))
end
end
l
end
function remove(s)
s = split(s, "")
pairs = find_matching_pairs(s)
t = trues(size(s))
# Set indices of parentheses enclosing nothing to false
foreach(p -> if p[1] +1 == p[2]; t[[p...]] = false; end, pairs)
# Set indices of redundant parentheses to false
for (p1, p2) in combinations(pairs, 2)
if p1[1] - 1 == p2[1] && p1[2] + 1 == p2[2]; t[[p1...]] = false; end
end
join(s[t])
end
inps = ["((a((bc)(de)))f)", "(((zbcd)(((e)fg))))", "ab((c))", "()", "((fgh()()()))", "()(abc())"]
outs = ["((a((bc)(de)))f)", "((zbcd)((e)fg))", "ab(c)", "", "(fgh)", "(abc)"]
@assert all(remove(inp) == out for (inp, out) in zip(inps, outs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment