Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. function longestPalindromicSubstring(input) {
  2. let longest = "";
  3. let lastChar = '';
  4. for (let i = 0; i < input.length; i++) {
  5. const char = input[i];
  6. const nextChar = input[i + 1]
  7.  
  8. let substr = '';
  9. let j = 0;
  10.  
  11. // e.g. "bananas" or "racecar"
  12. if (lastChar && nextChar && lastChar === nextChar) {
  13. substr = lastChar + char + nextChar;
  14. while (input[i - j] && input[i + j] && input[i - j] === input[i + j]) {
  15. substr = input.slice(i - j, i + j + 1)
  16. j++;
  17. }
  18. }
  19. // e.g. "millions"
  20. else if (char && lastChar && char === lastChar) {
  21. substr = lastChar + char;
  22. while (input[i - j - 1] && input[i + j] && input[i - j - 1] === input[i + j]) {
  23. substr = input.slice(i - j - 1, i + j + 1);
  24. j++;
  25. }
  26. }
  27.  
  28. if (substr.length > longest.length)
  29. longest = substr;
  30.  
  31. lastChar = char;
  32. }
  33. return longest;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement