• API
• FAQ
• Tools
• Archive
SHARE
TWEET

Untitled

a guest Jan 22nd, 2020 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. function longest_palindrome(s) {
2.     const palindromes = new Set();
3.     const finishedPalindromes = [];
4.
5.     const getLength = (i, c, isEven) => (i - c) * 2 + (isEven ? 0 : 1);
6.     const getPaired = (i, c, isEven) => i - (i - c) * 2 + (isEven ? 1 : 0);
7.
8.     for (let i = 0; i < s.length + 1; i++) {
9.       for (const p of palindromes) {
10.         const {isEven, center} = p;
11.         const probLength = getLength(i, center, isEven);
12.         if (i >= s.length || s[getPaired(i, center, isEven)] !== s[i]) {
13.           const length = probLength - 2;
14.           palindromes.delete(p);
15.           finishedPalindromes.push({...p, length, text: s.slice(getPaired(i - 1, center, isEven), i) })
16.         }
17.       }
18.       if (i >= s.length) {
19.         continue;
20.       }
21.       if (s[i + 1] === s[i - 1]) {
23.       }
24.       if (s[i] === s[i - 1]) {
25.         palindromes.add({isEven: true, center: i - 1});
26.       }
27.     }
28.
29.     let longest = s.length === 0 ?
30.         {center: 0, length: 0, isEven: true, text: ''} :
31.         {center: 0, length: 1, isEven: false, text: s[0]};
32.     for (const p of finishedPalindromes) {
33.       if (p.length > longest.length) {
34.         longest = p;
35.       }
36.     }
37.     return longest.text;
38.   }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.
Top