Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active February 28, 2017 21:01
Show Gist options
  • Save vitkarpov/dd38fb438da1ea6471d63de70e803216 to your computer and use it in GitHub Desktop.
Save vitkarpov/dd38fb438da1ea6471d63de70e803216 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", strings 1.3
/**
* Заменяет пробелы на %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('');
}
@alexeyten
Copy link

Небольшая оптимизация: останавливать цикл при i==j

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment