【今日湯底】
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.
Example:
'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'
(必須通過以下測試)
(ns kata.test
(:require [clojure.test :refer :all]
[kata :refer [switcheroo]]))
(deftest basic-tests
(is (= (switcheroo "abc") "bac"))
(is (= (switcheroo "aaabcccbaaa") "bbbacccabbb"))
(is (= (switcheroo "ccccc") "ccccc"))
(is (= (switcheroo "abababababababab") "babababababababa"))
(is (= (switcheroo "aaaaa") "bbbbb")))
【我的答案】
(ns kata)
(defn switcheroo [xs]
(->
(.replaceAll xs "a" "d")
(.replaceAll "b" "a")
(.replaceAll "d" "b"))
)
思路:
【其他人的答案】
(ns kata)
(defn switcheroo [xs]
(clojure.string/replace xs #"a|b" {"a" "b" "b" "a"})
)
(ns kata)
(defn- switch [c]
(cond
(= \a c) \b
(= \b c) \a
:else c))
(defn switcheroo [xs]
(->> (seq xs)
(map switch)
(apply str))
)