Skip to content

Commit

Permalink
feat: Refactor palindrome.clj for improved performance
Browse files Browse the repository at this point in the history
  • Loading branch information
vladimir-rurik committed Jul 21, 2024
1 parent ee90172 commit 81b7f8d
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions otus-02/src/otus_02/homework/palindrome.clj
Original file line number Diff line number Diff line change
@@ -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))))

This comment has been minimized.

Copy link
@Ivana-

Ivana- Jul 23, 2024

Actually do not need explisit boolean cast. And there is Java Charachter/IsAlphaOrNumeric static method


(defn normalize-char [c]
(string/lower-case (str c)))

This comment has been minimized.

Copy link
@Ivana-

Ivana- Jul 23, 2024

I guess there is Java static Charachter/toLower or similar method


(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))))))

This comment has been minimized.

Copy link
@Ivana-

Ivana- Jul 23, 2024

Yep, that was the goal!

0 comments on commit 81b7f8d

Please sign in to comment.