From 81b7f8d0f018a970152dbcbd9e2f80a838e654b8 Mon Sep 17 00:00:00 2001 From: Vladimir Rurik Date: Sun, 21 Jul 2024 19:35:11 +0300 Subject: [PATCH] feat: Refactor palindrome.clj for improved performance --- otus-02/src/otus_02/homework/palindrome.clj | 31 ++++++++++++++++----- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/otus-02/src/otus_02/homework/palindrome.clj b/otus-02/src/otus_02/homework/palindrome.clj index 706e540..b960bdd 100644 --- a/otus-02/src/otus_02/homework/palindrome.clj +++ b/otus-02/src/otus_02/homework/palindrome.clj @@ -1,13 +1,30 @@ (ns otus-02.homework.palindrome (:require [clojure.string :as string])) -(def non-alphanumeric-pattern #"\W+") +(def alphanumeric-pattern #"[a-zA-Z0-9\p{IsIdeographic}]") -(defn normalize-string [^String input] - (-> input - string/lower-case - (string/replace non-alphanumeric-pattern ""))) +(defn alphanumeric? [c] + (boolean (re-matches alphanumeric-pattern (str c)))) + +(defn normalize-char [c] + (string/lower-case (str c))) (defn is-palindrome [^String input] - (let [normalized-input (normalize-string input)] - (= normalized-input (string/reverse normalized-input)))) + (let [length (.length input)] + (loop [left 0 + right (dec length)] + (cond + (>= left right) true + + (not (alphanumeric? (.charAt input left))) + (recur (inc left) right) + + (not (alphanumeric? (.charAt input right))) + (recur left (dec right)) + + :else + (let [left-char (normalize-char (.charAt input left)) + right-char (normalize-char (.charAt input right))] + (if (= left-char right-char) + (recur (inc left) (dec right)) + false)))))) \ No newline at end of file