欢迎访问yhm138的博客园博客, 你可以通过 [RSS] 的方式持续关注博客更新

MyAvatar

yhm138

HelloWorld!

[Elixir/Erlang/Racket] 模式匹配,字符串,哈希表,格式化输出

https://leetcode.cn/problems/evaluate-the-bracket-pairs-of-a-string/solutions/2057593/s-by-yhm138_-nqxe/?orderBy=most_votes&languageTags=elixir-3

函数式编程三兄弟哈,leetcode什么时候支持haskell?

Elixir

名词解释

:binary.encode_unsigned(c)   codepoint转到bitstring
<< >>     空的bitstring
res<>  <<"hello">>    拼接2个bitstring
?\s                拿到字符's'的codepoint
??      拿到字符'?'的codepoint
%{}     空字典

代码

defmodule Solution do
  @spec evaluate(s :: String.t, knowledge :: [[String.t]]) :: String.t
  def evaluate(s, knowledge) do
    dict = knowledge |> Enum.reduce(%{}, fn [k, v], acc -> Map.put(acc, k, v) end)
    # dict = Enum.into(Enum.map(knowledge, fn [key, val] -> {String.to_existing_atom(key), val} end), %{})
    for << c<-s >>, reduce: {false, <<>>, <<>>} do
        {add_key, key, res} ->
            cond do
                c==?\( -> 
                    {true, key, res}
                c==?\) ->
                    {false,  << >>,  res<> Map.get(dict,key,<<"?">>) }
                true ->
                    case add_key do
                        true->{add_key, key<>:binary.encode_unsigned(c), res}
                        false->{add_key, key, res<>:binary.encode_unsigned(c)}
                    end
                    
            end
    end
    |> elem(2)   #下标从0开始,取三元组里的res
  end
end


# :io.format("before, The value of res is: ~p~n", [res])

Erlang

名词解释

iolist_to_binary([Res, <<"?">>])    拼接bitstring
<< >>   空的bitstring
element(3,Res)     元组的第3个元素
$(  拿到'('的codepoint
erlang:binary_to_list   bitstring转list

代码


getOrDefault(Dict, Key, DefaultValue) ->
    case dict:find(Key, Dict) of
        {ok, Value} ->
            Value;
        error ->
            DefaultValue
    end.


evaluate(S, Knowledge) ->
    Dict = lists:foldl(fun([K, V], Acc) -> dict:store(K, V, Acc) end, dict:new(), Knowledge),
    MyFunc =fun(C, {AddKey, Key, Res}) ->
                    case C of
                        $( -> {true, Key, Res};
                        $) -> {false, <<>>, iolist_to_binary([Res, getOrDefault(Dict,Key, <<"?">>)])};
                        _  -> 
                            case AddKey of
                                true  -> {AddKey, iolist_to_binary([Key,C]), Res};
                                false -> {AddKey, Key, iolist_to_binary([Res,C])}
                            end
                    end
            end,
    Res = lists:foldl(MyFunc, {false,<< >>,<< >>}, erlang:binary_to_list(S)),
    element(3,Res).


% io:format("Sum=~p   ~n", [Sum]),

Racket

名词解释

(car ele)  取ele的第一个元素
(cadr ele) 取ele的第二个元素
(string->list s)   bitstring 切分为list
(string ele)    可以把#\(  转成"("
(string-append key c)    字符串拼接,key在前,c在后

代码

(define (get-or-default dict key default-value)
  (let ([result (hash-ref dict key 'not-found)])
    (if (eq? result 'not-found) default-value result))
)

(define/contract (evaluate s knowledge)
  (-> string? (listof (listof string?)) string?)
    (define my-dict (make-hash))
    (for-each
        (lambda (ele) (
            hash-set! my-dict (car ele) (cadr ele)
        )) 
    knowledge)
    

    (define my-list (string->list s))
    (displayln my-list)
    (define final_acc (foldl 
                                (lambda (ele acc)  ;iterator 和  acc
                                      (define c (string ele))
                                      (define addkey (list-ref acc 0))
                                      (define key (list-ref acc 1))
                                      (define res (list-ref acc 2))
                                       (match c
                                            ["("     (list #t key res)]
                                            [")"     (list #f ""  (string-append res (get-or-default my-dict key "?")) )]
                                            [else 
                                                (match addkey 
                                                    [#t  (list addkey (string-append key c) res)]
                                                    [#f  (list addkey key (string-append res c))]
                                                )
                                            ]
                                        )
                                ) 
                                (list  #f "" "")  ;acc初始值
                                my-list))         ;foldl主体
    (define ret (list-ref final_acc 2))
    ret
)
posted @ 2023-01-12 11:07  yhm138  阅读(76)  评论(0编辑  收藏  举报