LeetCode 125. Valid Palindrome (LaTeX)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Example

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

Notes

For the purpose of this problem, we define empty string as valid palindrome.

Solution

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{expl3}
\usepackage{datetime2}


\begin{document}

\ExplSyntaxOn

\cs_generate_variant:Nn \str_map_variable:nNn {VNn}

\cs_set:Npn \get_charcode:n #1 {
	\int_eval:n {`#1}
}

\cs_set:Npn \valid_palindrome:n #1 {
	\str_gset:Nn \g_tmpa_str {#1}
	\str_gclear:N \g_tmpb_str

	\str_map_variable:VNn \g_tmpa_str \l_tmpa_str {
		\exp_args:NNx \int_set:Nn \l_tmpa_int { \exp_args:NV \get_charcode:n \l_tmpa_str }
		\bool_if:nT {
			\int_compare_p:n { 47 < \l_tmpa_int < 58 } ||
			\int_compare_p:n { 64 < \l_tmpa_int < 91 } ||
			\int_compare_p:n { 96 < \l_tmpa_int < 123 }
		}
		{\str_gput_right:Nx \g_tmpb_str {\tl_lower_case:n \l_tmpa_str}}
	}


	\par processed~string:~\cs_meaning:N \g_tmpb_str
	\str_gset_eq:NN \g_tmpa_str \g_tmpb_str
	\tl_reverse:N \g_tmpa_str
	\par reversed~string:~\cs_meaning:N \g_tmpa_str
	\str_if_eq:NNTF \g_tmpa_str \g_tmpb_str
		{
		\tl_gset:Nn \g_tmpa_tl {true}
		} {
		\tl_gset:Nn \g_tmpa_tl {false}
		}
}

\newcommand{\validpalindrome}[1]{
	\valid_palindrome:n {#1}
	\par\textbf{result:~\tl_use:N \g_tmpa_tl}
}

\ExplSyntaxOff


\validpalindrome{A man, a plan, a canal: Panama}
\validpalindrome{hello}

\DTMNow

\end{document}

Output

processed string: macro:->amanaplanacanalpanama
reversed string: macro:->amanaplanacanalpanama
result: true
processed string: macro:->hello
reversed string: macro:->olleh
result: false
2020-06-12 11:17:00-04:00