{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

344. Reverse String

\n", "
\n", "\n", "\n", "

Write a function that reverses a string. The input string is given as an array of characters char[].

\n", "\n", "

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

\n", "\n", "

You may assume all the characters consist of printable ascii characters.

\n", "\n", "

 

\n", "\n", "
\n", "

Example 1:

\n", "\n", "
Input: [\"h\",\"e\",\"l\",\"l\",\"o\"]\n",
    "Output: [\"o\",\"l\",\"l\",\"e\",\"h\"]\n",
    "
\n", "\n", "
\n", "

Example 2:

\n", "\n", "
Input: [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n",
    "Output: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n",
    "
\n", "
\n", "
\n", "\n", "\n", "

 

\n", "Source \n", "
\n", "\n", "

Code

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def reverse_list(stringlist):\n", " \"\"\"Iterative approach\"\"\"\n", " if not stringlist:\n", " return\n", " left = 0\n", " right = len(stringlist)-1\n", " while left < right:\n", " stringlist[left], stringlist[right] = stringlist[right], stringlist[left]\n", " left += 1\n", " right -= 1\n", " return stringlist" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def reverse_list(stringlist):\n", " \"\"\"Iterative approach\"\"\"\n", " n = len(stringlist)\n", " # base case\n", " if n <= 1:\n", " return stringlist\n", " # recursion\n", " return(reverse_list(stringlist[n//2:]) + reverse_list(stringlist[:n//2]))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def reverse_list(stringlist):\n", " \"\"\"cheating\"\"\"\n", " mylist[:] = mylist[::-1] # modified in place\n", " # return mylist[::-1] # NOT modified in place" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Check

" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['o', 'l', 'l', 'e', 'h']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stringlist = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n", "reverse_list(stringlist)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['h', 'a', 'n', 'n', 'a', 'H']" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stringlist = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n", "reverse_list(stringlist)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }