ATTENTION: THERE IS AN ERROR in this video when explaining the for loop conditions for the main part of the function isPalindrome. The error is that dividing by 2 and subtracting 1 as suggested verbally actually would not work. The correct conditions should be the floor the outcome of the division:
for (let i = 0; i (less than) Math.floor(removedString.length / 2); i += 1)
Explanation:
In my example with 'racecar', the length would be 7, divided by 2 would be 3.5, and either flooring or subtracting 1 would have the same effect of stopping the loop after index 2 is inspected, which is fine since 3 is the middle index.
HOWEVER, in an even length example, such as 'pullup', the length would be 6, divided by 2 would be 3, and subtracting 1 would be 2, meaning the loop would stop at index 1, but it actually needs to also check index 2 and compare with index 4. For this reason, we must use Math.floor, which will result in 6 / 2 = 3 and the floor would have no effect, and the loop would continue to index 2.
The solution in the video would work because I accidentally only go to removedString.length - 1 (instead of dividing by 2 first, then further subtracting 1 like I suggested verbally), which actually will work in every scenario. However, it is not optimal.
In addition, I should also check for numbers, which can be found at 48-57. The helper function if statement could instead look like this to accommodate the numbers:
if ((charCode (greater than or equal to) 97 && charCode (less than or equal to) 122)
|| (charCode (greater than or equal to) 48 && charCode (less than or equal to) 57))
Sorry about that!
In this video I go over 1 approach for solving isPalindrome.
Further optimization:
Although this method is fast enough (linear), it does use a lot more memory, and can actually be simplified using a 2 pointer approach starting at leftmost and rightmost indices. For this approach you would exit the while loop once the index is the same. At each pointer, check if the character on both sides is either alpha or numeric. If it isn't, move the pointer(s) inward until they are both valid, then compare. This will use a lot less memory and be O(1) in memory use as all you will use is the variables to hold the 2 pointer positions.
Nesta página do site você pode assistir ao vídeo on-line isPalindrome algorithm coded and explained - Javascript duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Techtonics 12 Março 2020, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 48 vezes e gostou 0 espectadores. Boa visualização!