LeetCode 345. Reverse Vowels of a String (LaTeX)

Write a function that takes a string as input and reverse only the vowels of a string.

Example

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Notes

The vowels does not include the letter "y".

Solution

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

\begin{document}

\ExplSyntaxOn

% stack based method
% https://leetcode.com/problems/reverse-vowels-of-a-string/discuss/667829/Python%3A-use-stack

\str_new:N \g_vowels_str
\str_gset:Nn \g_vowels_str {aeiouAEIOU}

\str_new:N \g_tmpc_str

\par vowels:~\cs_meaning:N \g_vowels_str

\cs_generate_variant:Nn \str_if_in:NnTF {NVTF}

\cs_set:Npn \reverse_vowel:n #1 {
    \str_gset:Nn \g_tmpc_str {#1}

    % clear the stack
    \seq_gclear:N \g_tmpa_seq

    \str_map_variable:NNn \g_tmpc_str \l_tmpa_str {
        \str_if_in:NVTF \g_vowels_str {\l_tmpa_str} {
            \seq_gput_right:NV \g_tmpa_seq {\l_tmpa_str}
        } {}
    }

    \par vowel~stack:~\cs_meaning:N \g_tmpa_seq
    \str_gclear:N \g_tmpa_str % result string
    \str_map_variable:NNn \g_tmpc_str \l_tmpa_str {
        \str_if_in:NVTF \g_vowels_str {\l_tmpa_str} {
            \seq_gpop_right:NN \g_tmpa_seq \l_tmpb_str
            \str_gput_right:NV \g_tmpa_str {\l_tmpb_str}
        }
        {
            \str_gput_right:NV \g_tmpa_str {\l_tmpa_str}
        }
    }

    \str_gset_eq:NN \result \g_tmpa_str
}

\reverse_vowel:n {hello}
\par \textbf{result:\ \str_use:N \g_tmpa_str}
\reverse_vowel:n {Aa}
\par \textbf{result:\ \str_use:N \g_tmpa_str}
\reverse_vowel:n {bookeeper}
\par \textbf{result:\ \str_use:N \g_tmpa_str}

\ExplSyntaxOff

\DTMNow

\end{document}

Output

vowels: macro:->aeiouAEIOU
vowel stack: macro:->\s__seq \__seq_item:n {e}\__seq_item:n {o}
result: holle
vowel stack: macro:->\s__seq \__seq_item:n {A}\__seq_item:n {a}
result: aA
vowel stack: macro:->\s__seq \__seq_item:n {o}\__seq_item:n {o}\__seq_item:n {e}\__seq_item:n {e}\__seq_item:n {e}
result: beekeopor
2020-06-11 01:17:54-04:00