{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Solution Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem: Format license keys.\n", "\n", "See the [LeetCode](https://leetcode.com/problems/license-key-formatting/) problem page.\n", "\n", "
\n",
    "Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.\n",
    "\n",
    "We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.\n",
    "\n",
    "So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.\n",
    "\n",
    "Example 1:\n",
    "Input: S = \"2-4A0r7-4k\", K = 4\n",
    "\n",
    "Output: \"24A0-R74K\"\n",
    "\n",
    "Explanation: The string S has been split into two parts, each part has 4 characters.\n",
    "Example 2:\n",
    "Input: S = \"2-4A0r7-4k\", K = 3\n",
    "\n",
    "Output: \"24-A0R-74K\"\n",
    "\n",
    "Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said above.\n",
    "\n",
    "Note:\n",
    "The length of string S will not exceed 12,000, and K is a positive integer.\n",
    "String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).\n",
    "String S is non-empty.\n",
    "
\n", "\n", "* [Constraints](#Constraints)\n", "* [Test Cases](#Test-Cases)\n", "* [Algorithm](#Algorithm)\n", "* [Code](#Code)\n", "* [Unit Test](#Unit-Test)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Constraints\n", "\n", "* Is the output a string?\n", " * Yes\n", "* Can we change the input string?\n", " * No, you can't modify the input string\n", "* Can we assume the inputs are valid?\n", " * No\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "* None -> TypeError\n", "* '---', k=3 -> ''\n", "* '2-4A0r7-4k', k=3 -> '24-A0R-74K'\n", "* '2-4A0r7-4k', k=4 -> '24A0-R74K'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "* Loop through each character in the license key backwards, keeping a count of the number of chars we've reached so far, while inserting each character into a result list (convert to upper case)\n", " * If we reach a '-', skip it\n", " * Whenever we reach a char count of k, append a '-' character to the result list, reset the char count\n", "* Careful that we don't have a leading '-', which we might hit with test case: '2-4A0r7-4k', k=4 -> '24A0-R74K'\n", "* Reverse the result list and return it\n", "\n", "Complexity:\n", "* Time: O(n)\n", "* Space: O(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Solution(object):\n", "\n", " def format_license_key(self, license_key, k):\n", " if license_key is None:\n", " raise TypeError('license_key must be a str')\n", " if not license_key:\n", " raise ValueError('license_key must not be empty')\n", " formatted_license_key = []\n", " num_chars = 0\n", " for char in license_key[::-1]:\n", " if char == '-':\n", " continue\n", " num_chars += 1\n", " formatted_license_key.append(char.upper())\n", " if num_chars >= k:\n", " formatted_license_key.append('-')\n", " num_chars = 0\n", " if formatted_license_key and formatted_license_key[-1] == '-':\n", " formatted_license_key.pop(-1)\n", " return ''.join(formatted_license_key[::-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_format_license_key.py\n" ] } ], "source": [ "%%writefile test_format_license_key.py\n", "import unittest\n", "\n", "\n", "class TestSolution(unittest.TestCase):\n", "\n", " def test_format_license_key(self):\n", " solution = Solution()\n", " self.assertRaises(TypeError, solution.format_license_key, None, None)\n", " license_key = '---'\n", " k = 3\n", " expected = ''\n", " self.assertEqual(solution.format_license_key(license_key, k), expected)\n", " license_key = '2-4A0r7-4k'\n", " k = 3\n", " expected = '24-A0R-74K'\n", " self.assertEqual(solution.format_license_key(license_key, k), expected)\n", " license_key = '2-4A0r7-4k'\n", " k = 4\n", " expected = '24A0-R74K'\n", " self.assertEqual(solution.format_license_key(license_key, k), expected)\n", " print('Success: test_format_license_key')\n", "\n", "def main():\n", " test = TestSolution()\n", " test.test_format_license_key()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success: test_format_license_key\n" ] } ], "source": [ "%run -i test_format_license_key.py" ] } ], "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.2" } }, "nbformat": 4, "nbformat_minor": 1 }