Skip to content

Commit

Permalink
[chore] update approach, add type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
gitgik committed Jan 26, 2021
1 parent 7ff40b2 commit 13cd928
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions strings/reverse_string_words.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,30 @@
"Follow-up: given a mutable string representation, can you perform this operation in-place?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Approach \n",
"\n",
"Since strings are immutable, a mutable string can be represented as a list of characters in a buffer e.g `['h','e','l','l','o',' ','w','o','r','l','d']` == 'hello world'\n",
"\n",
"First we reverse entire string to get `'dlrow olleh'`, then we reverse each word within the string to obtain original words."
]
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"def reverse(string_list: str, start: int, end: int) -> str:\n",
"def reverse(string_list: list, start: int, end: int) -> str:\n",
" while start < end:\n",
" string_list[start], string_list[end] = string_list[end], string_list[start]\n",
" start += 1\n",
" end -= 1\n",
"\n",
"def reverse_words(string_list):\n",
"def reverse_words(string_list: list) -> str:\n",
" reverse(string_list, 0, len(string_list) - 1)\n",
" start = 0\n",
" for i in range(len(string_list)):\n",
Expand All @@ -37,22 +48,23 @@
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'there hi'"
"'there hello well'"
]
},
"execution_count": 29,
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"reverse_words(list(\"hi there\"))"
"string_list = list(\"well hello there\")\n",
"reverse_words(string_list)"
]
},
{
Expand Down

0 comments on commit 13cd928

Please sign in to comment.