Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <title>JS Bin</title>
- </head>
- <body>
- <script>
- /* Returns if a text is a palindrome */
- function isPalindrome(text) {
- let valid = true;
- // Iterate over half of the characters
- for (var i = 0; i < text.length / 2; i++) {
- if (text.charAt(i) !== text.charAt(text.length - i - 1)) valid = false;
- }
- // Returns if its valid
- return valid;
- }
- /* Returns the character code at the position */
- function getCharCode(text, pos) {
- return text.charCodeAt(pos) - 'a'.charCodeAt(0);
- }
- /* Returns if a text is a permutation of a palindrome */
- function isPermutationofPalindrome(text) {
- const hash = new Array(26);
- // Goes over each character
- for (let i = 0; i < text.length; i++) {
- const charCode = getCharCode(text, i);
- hash[charCode] = (hash[charCode] || 0) + 1;
- }
- // Counts the number of characters that appear even times
- let evenCount = 0;
- for (let i = 0; i < hash.length; i++) {
- if (hash[i] % 2 === 1) evenCount += 1;
- }
- // It can be a palindrome if there is at most one even character
- return evenCount <= 1;
- }
- // Test
- //const word = 'catac';
- const word = 'xyz';
- document.write(`${word}:<br/>`);
- document.write(`isPalindrome: ${isPalindrome(word)}<br/>`);
- document.write(`isPermutationofPalindrome: ${isPermutationofPalindrome(word)}<br/>`);
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment