Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active March 23, 2017 07:13
Show Gist options
  • Save vitkarpov/eb4e4946f12a80147191868a31fa89a0 to your computer and use it in GitHub Desktop.
Save vitkarpov/eb4e4946f12a80147191868a31fa89a0 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", strings, 1.4
/**
* Проверяет является ли переданная строка
* перестановкой палиндрома.
* Работает за O(n) и требует O(n) дополнительной памяти.
*
* @param {string} str
* @returns {boolean}
*/
function isPalindromPermutation(str) {
const counters = {};
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (_isCharALetter(char)) {
counters[char] = counters[char] ? counters[char] + 1 : 1;
}
}
let foundOdd = false;
let isMaxOneOdd = true;
Object.keys(counters).forEach((char) => {
if (counters[char] % 2 === 1) {
if (foundOdd) {
isMaxOneOdd = false;
}
foundOdd = true;
}
});
return isMaxOneOdd;
}
/**
* Проверяет является ли сивмол буквой алфавита.
* В палиндромах не учитываются символы ?,. и т.д. — только буквы.
*/
function _isCharALetter(char) {
const charCode = char.toLowerCase().charCodeAt(0);
const latinBounds = ['a'.charCodeAt(0), 'z'.charCodeAt(0)];
const cyrillicBounds = ['а'.charCodeAt(0), 'я'.charCodeAt(0)];
return (
charCode >= latinBounds[0] && charCode <= latinBounds[1] ||
charCode >= cyrillicBounds[0] && charCode <= cyrillicBounds[1]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment