Simplify reverse string code, improve algorithm readability (#183)

This commit is contained in:
Ammar Najjar 2017-04-17 00:19:49 +02:00 committed by Donne Martin
parent 1d2b138344
commit 83ad7ff23a

View File

@ -65,7 +65,7 @@
"Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.\n",
"\n",
"* Iterate len(string)/2 times, starting with i = 0:\n",
" * Swap i and len(string) - 1 - i\n",
" * Swap char with index (i) and char with index (len(string) - 1 - i)\n",
" * Increment i\n",
"\n",
"Complexity:\n",
@ -97,12 +97,11 @@
"class ReverseString(object):\n",
"\n",
" def reverse(self, chars):\n",
" if chars is None or not chars:\n",
" return chars\n",
" size = len(chars)\n",
" for i in range(size // 2):\n",
" chars[i], chars[size - 1 - i] = \\\n",
" chars[size - 1 - i], chars[i]\n",
" if chars:\n",
" size = len(chars)\n",
" for i in range(size // 2):\n",
" chars[i], chars[size - 1 - i] = \\\n",
" chars[size - 1 - i], chars[i]\n",
" return chars"
]
},
@ -126,14 +125,14 @@
"class ReverseStringAlt(object):\n",
"\n",
" def reverse_string_alt(string):\n",
" if string is None or not string:\n",
" return string\n",
" return string[::-1]\n",
" if string:\n",
" return string[::-1]\n",
" return string\n",
"\n",
" def reverse_string_alt2(string):\n",
" if string is None or not string:\n",
" return string\n",
" return ''.join(reversed(string))"
" if string:\n",
" return ''.join(reversed(string))\n",
" return string"
]
},
{