|
| 1 | +// URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient |
| 2 | +// space at the end to hold the additional characters, and that you are given the "true" length of the string. |
| 3 | + |
| 4 | +const assert = require("assert"); |
| 5 | + |
| 6 | +/** |
| 7 | + * URLifies an input string by replacing ' ' with '%20' and returning the modified string |
| 8 | + * @param {string} str input string to modify |
| 9 | + * @param {int} trueLength the "true" length of the str without trailing spaces |
| 10 | + * @return {string} output URLified string |
| 11 | + * |
| 12 | + * Since we cannot mutate a string in javascript, we need to use an external data structure, like an array. |
| 13 | + * Creating a new data structure takes up O(N) space, where N is the length of the str. |
| 14 | + * We can loop through the array from the end of the true length to the start, while keeping count of two indexes. |
| 15 | + * If we encounter a space within the parameters of the word's true length, we can overwrite the element at that index |
| 16 | + * and the previous two indices with "%20", and decrement the index by 3, all of which are O(1) operations. |
| 17 | + * Alteranatively, we just overwrite the index of the str length counter with the index of the true length counter, |
| 18 | + * and decrement the index by 1, which is also just an O(1) operation. |
| 19 | + * When we're done traversing the array, we can simply return the joined array to return a string. |
| 20 | + * |
| 21 | + * Runtime: O(N) |
| 22 | + * Space: O(N) |
| 23 | + * |
| 24 | + */ |
| 25 | +const urlify = (str, trueLength) => { |
| 26 | + const strArr = str.split(""); |
| 27 | + let idx = str.length - 1; |
| 28 | + |
| 29 | + for (let i = trueLength - 1; i >= 0; i--) { |
| 30 | + if (strArr[i] === " ") { |
| 31 | + strArr[idx] = "0"; |
| 32 | + strArr[idx - 1] = "2"; |
| 33 | + strArr[idx - 2] = "%"; |
| 34 | + idx -= 3; |
| 35 | + } else { |
| 36 | + strArr[idx] = strArr[i]; |
| 37 | + idx -= 1; |
| 38 | + } |
| 39 | + } |
| 40 | + return strArr.join(""); |
| 41 | +}; |
| 42 | + |
| 43 | +describe(module.filename, () => { |
| 44 | + it("should return the modified string with %20 in place of spaces", () => { |
| 45 | + assert.equal(urlify("Mr John Smith ", 13), "Mr%20John%20Smith"); |
| 46 | + }); |
| 47 | + it("should not modify a string with no spaces", () => { |
| 48 | + assert.equal(urlify("techqueria", 10), "techqueria"); |
| 49 | + }); |
| 50 | +}); |
0 commit comments