{ "cells": [ { "cell_type": "markdown", "id": "65ef957c-de24-4f8e-af58-84247c133bba", "metadata": {}, "source": [ "# [Array / String](https://leetcode.com/studyplan/leetcode-75/)" ] }, { "cell_type": "markdown", "id": "d62e677f-59f1-48c9-aca0-8eeb5cda4614", "metadata": {}, "source": [ "## [151. Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/?envType=study-plan-v2&envId=leetcode-75)\n", "\n", "Medium\n", "\n", "Given an input string s, reverse the order of the words.\n", "\n", "A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.\n", "\n", "Return a string of the words in reverse order concatenated by a single space.\n", "\n", "Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. \n", "\n", "Example 1:\n", "\n", " Input: s = \"the sky is blue\"\n", " Output: \"blue is sky the\"\n", " \n", "Example 2:\n", "\n", " Input: s = \" hello world \"\n", " Output: \"world hello\"\n", " Explanation: Your reversed string should not contain leading or trailing spaces.\n", " \n", "Example 3:\n", "\n", " Input: s = \"a good example\"\n", " Output: \"example good a\"\n", " Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n", " \n", "Constraints:\n", "\n", " 1 <= s.length <= 104\n", " s contains English letters (upper-case and lower-case), digits, and spaces ' '.\n", " There is at least one word in s.\n", " \n", "Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?" ] }, { "cell_type": "code", "execution_count": 3, "id": "b473082e-1b9b-4627-b642-43b7c38b9541", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'example good a'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import re\n", "\n", "def reverseWords(s: str) -> str:\n", " return ' '.join(re.sub(r'\\s{2,}', ' ', s).strip().split(' ')[::-1])\n", "\n", "reverseWords('a good example')" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }