Skip to content

Instantly share code, notes, and snippets.

@ray-sh
Last active January 20, 2018 15:01
Show Gist options
  • Save ray-sh/d55f5c7d06b6932d786ad736bec6df37 to your computer and use it in GitHub Desktop.
Save ray-sh/d55f5c7d06b6932d786ad736bec6df37 to your computer and use it in GitHub Desktop.
括号匹配算法
问题:
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
基本思想:在算法中设置一个栈,每读入一个括号,若是右括号,则或者与栈顶匹配的左括号相互消解,或者是不合法的情况;若是左括号,则直接压入栈中。
若括号匹配,在算法的开始和结束时,栈都应该是空的。
defmodule Challenge do
def valid_braces(braces), do: valid_braces(braces, [])
def valid_braces("(" <> rest, opened), do: valid_braces(rest, ["(" | opened])
def valid_braces("[" <> rest, opened), do: valid_braces(rest, ["[" | opened])
def valid_braces("{" <> rest, opened), do: valid_braces(rest, ["{" | opened])
def valid_braces(")" <> rest, ["(" | opened]), do: valid_braces(rest, opened)
def valid_braces("]" <> rest, ["[" | opened]), do: valid_braces(rest, opened)
def valid_braces("}" <> rest, ["{" | opened]), do: valid_braces(rest, opened)
def valid_braces("", []), do: true
def valid_braces(_, _), do: false
end
defmodule Challenge do
def valid_braces(braces, length \\ 0) do
length = String.length(braces)
new_braces = braces
|> String.replace("()", "")
|> String.replace("{}", "")
|> String.replace("[]", "")
cond do
(String.length(new_braces) == length) ->
false
(new_braces == "") ->
true
true ->
valid_braces(new_braces, length)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment