-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Refactor palindrome.clj for improved performance
- Loading branch information
1 parent
ee90172
commit 81b7f8d
Showing
1 changed file
with
24 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Sorry, something went wrong. |
||
|
||
(defn normalize-char [c] | ||
(string/lower-case (str c))) | ||
This comment has been minimized.
Sorry, something went wrong. |
||
|
||
(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.
Sorry, something went wrong. |
Actually do not need explisit boolean cast. And there is Java
Charachter/IsAlphaOrNumeric
static method