{ "cells": [ { "cell_type": "markdown", "source": [ "Given a string `s`, return _the longest palindromic substring_ in `s`.\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " Input: s = \"babad\"\n", " Output: \"bab\"\n", " **Note:** \"aba\" is also a valid answer.\n", "\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: s = \"cbbd\"\n", " Output: \"bb\"\n", "\n", "\n", "**Example 3:**\n", "\n", "\n", "\n", " Input: s = \"a\"\n", " Output: \"a\"\n", "\n", "\n", "**Example 4:**\n", "\n", "\n", "\n", " Input: s = \"ac\"\n", " Output: \"a\"\n", "\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * `1 <= s.length <= 1000`\n", " * `s` consist of only digits and English letters (lower-case and/or upper-case)," ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "_longest_palindrome (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function longest_palindrome(s::String)::AbstractString\n", " res = \"\"\n", " for i in 1:length(s)\n", " s_odd = _longest_palindrome(s, i, i)\n", " if length(s_odd) > length(res)\n", " res = s_odd\n", " end\n", " s_even = _longest_palindrome(s, i, i + 1)\n", " if length(s_even) > length(res)\n", " res = s_even\n", " end\n", " end\n", " return res\n", "end\n", "\n", "function _longest_palindrome(s, l, r)\n", " while l >= 1 && r <= length(s) && s[l] == s[r]\n", " l -= 1\n", " r += 1\n", " end\n", " return SubString(s, l + 1, r - 1)\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }