Skip to content

Commit

Permalink
[chore] add string reversal
Browse files Browse the repository at this point in the history
  • Loading branch information
gitgik committed Jan 26, 2021
1 parent 24344d8 commit 7ff40b2
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions strings/reverse_string_words.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Problem\n",
"\n",
"Given a string of words delimited by spaces, reverse the words in string. For example, given \"hello world here\", return \"here world hello\"\n",
"\n",
"Follow-up: given a mutable string representation, can you perform this operation in-place?"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"def reverse(string_list: str, 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",
" reverse(string_list, 0, len(string_list) - 1)\n",
" start = 0\n",
" for i in range(len(string_list)):\n",
" if string_list[i] == \" \":\n",
" reverse(string_list, start, i - 1)\n",
" start = i + 1\n",
" # we need to reverse the last sub-string\n",
" reverse(string_list, start, len(string_list) - 1)\n",
" return \"\".join(string_list)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'there hi'"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"reverse_words(list(\"hi there\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
}
],
"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.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

0 comments on commit 7ff40b2

Please sign in to comment.