Created
January 2, 2017 23:31
-
-
Save ymer/5c8d3ccd258cafefaaef603713f486e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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