|
| 1 | +/** |
| 2 | + * alphaNumericPlaindrome should return true if the string has alphanumeric characters that are palindrome irrespective of special characters and the letter case |
| 3 | + * @param {string} str the string to check |
| 4 | + * @returns `Boolean` |
| 5 | + */ |
| 6 | + |
| 7 | +/***************************************************************************** |
| 8 | + * What is a palindrome? https://en.wikipedia.org/wiki/Palindrome |
| 9 | + * |
| 10 | + * The function alphaNumericPlaindrome() recieves a sting with varying formats |
| 11 | + * like "racecar", "RaceCar", and "race CAR" |
| 12 | + * The string can also have special characters |
| 13 | + * like "2A3*3a2", "2A3 3a2", and "2_A3*3#A2" |
| 14 | + * |
| 15 | + * But the catch is, we have to check only if the alphanumeric characters |
| 16 | + * are palindrome i.e remove spaces, symbols, punctuations etc |
| 17 | + * and the case of the characters doesn't matter |
| 18 | + * |
| 19 | + * This is one of the questions/projects that we have to solve for the |
| 20 | + * JavaScript Algorithms and Data Structures course on https://www.freecodecamp.org |
| 21 | + * |
| 22 | + * Author -- Syed Fasiuddin |
| 23 | + * https://github.com/SyedFasiuddin |
| 24 | + * |
| 25 | + ****************************************************************************/ |
| 26 | + |
| 27 | +const alphaNumericPlaindrome = (str) => { |
| 28 | + // removing all the special characters and turning everything to lowercase |
| 29 | + let newStr = str.replace(/[^a-zA-Z0-9]*/g, "").toLowerCase(); |
| 30 | + // the newStr variable is a string and only has alphanumeric characters all in lowercase |
| 31 | + |
| 32 | + // making an array of individual characters as it's elements |
| 33 | + let arr = newStr.split("") |
| 34 | + |
| 35 | + // setting a variable to see if change occurs to it |
| 36 | + let palin = 0; |
| 37 | + |
| 38 | + // making a copy of arr with spread operator |
| 39 | + let arrRev = [...arr]; |
| 40 | + // you can use arrRev.reverse() to reverse the array |
| 41 | + // or else you can use the below method |
| 42 | + |
| 43 | + // iterate through the arr and check the condition of palindrome |
| 44 | + for (let i = 0; i < arr.length; i++) { |
| 45 | + if (arr[i] !== arrRev[arr.length - 1 - i]) { |
| 46 | + // if the string is not palindrome then we change palin varaible to 1 |
| 47 | + palin = 1 |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // if the string is palindrome then palin variable is never changed |
| 52 | + if (palin == 0) return true; |
| 53 | + else return false; |
| 54 | +} |
| 55 | + |
| 56 | + |
| 57 | +// test cases |
| 58 | +// alphaNumericPlaindrome("eye"); |
| 59 | +// alphaNumericPlaindrome("0_0 (: /-\ :) 0-0") |
| 60 | +// alphaNumericPlaindrome("five|\_/|four") |
| 61 | +// alphaNumericPlaindrome("A man, a plan, a canal. Panama") |
| 62 | + |
| 63 | + |
| 64 | +export { alphaNumericPlaindrome } |
0 commit comments