Last active
March 23, 2017 07:13
-
-
Save vitkarpov/eb4e4946f12a80147191868a31fa89a0 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", strings, 1.4
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
/** | |
* Проверяет является ли переданная строка | |
* перестановкой палиндрома. | |
* Работает за 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