Last active
February 28, 2017 21:01
-
-
Save vitkarpov/dd38fb438da1ea6471d63de70e803216 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", strings 1.3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Заменяет пробелы на %20. | |
* Выполняет замену «на месте». | |
* | |
* @param {string} str | |
* @returns {string} | |
*/ | |
function replaceSpaces(str) { | |
str = str.split(''); | |
let spaces = 0; | |
for (let i = 0; i < str.length; i++) { | |
if (str[i] === ' ') { | |
spaces++; | |
} | |
} | |
// i - указатель на текущий символ исходной строки | |
// j - указатель на текущий символ новой строки | |
// i < j, ∀ i,j | |
for (let i = str.length - 1, j = str.length + 2 * spaces; i >= 0; i--) { | |
if (str[i] === ' ') { | |
str[j - 1] = '0'; | |
str[j - 2] = '2'; | |
str[j - 3] = '%'; | |
j -= 3; | |
} else { | |
str[j - 1] = str[i]; | |
j -= 1; | |
} | |
} | |
return str.join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Небольшая оптимизация: останавливать цикл при i==j