AlgoDaily Solution
1var assert = require('assert');
2
3const longestPalindrome = (str) => {
4 if (!str || str.length <= 1) {
5 return str;
6 }
7
8 let longest = str.substring(0, 1);
9 for (let i = 0; i < str.length; i++) {
10 let temp = expand(str, i, i);
11 if (temp.length > longest.length) {
12 longest = temp;
13 }
14 temp = expand(str, i, i + 1);
15 if (temp.length > longest.length) {
16 longest = temp;
17 }
18 }
19 return longest;
20};
21
22const expand = (str, begin, end) => {
23 while (begin >= 0 && end <= str.length - 1 && str[begin] === str[end]) {
24 begin--;
25 end++;
26 }
27 return str.substring(begin + 1, end);
28};
29
30try {
31 assert.equal(longestPalindrome(''), '');
32
33 console.log('PASSED: ' + "`longestPalindrome('')` should return `''`");
34} catch (err) {
35 console.log(err);
36}
37
38try {
39 assert.equal(longestPalindrome('algodaily'), 'a');
40
41 console.log(
42 'PASSED: ' + "`longestPalindrome('algodaily')` should return `'a'`"
43 );
44} catch (err) {
45 console.log(err);
46}
47
48try {
49 assert.equal(longestPalindrome('gymmyg'), 'gymmyg');
50
51 console.log(
52 'PASSED: ' + "`longestPalindrome('gymmyg')` should return `'gymmyg'`"
53 );
54} catch (err) {
55 console.log(err);
56}
57
58try {
59 assert.equal(longestPalindrome('nasduhuuhdousan'), 'huuh');
60
61 console.log(
62 'PASSED: ' + "`longestPalindrome('nasduhuuhdousan')` should return `'huuh'`"
63 );
64} catch (err) {
65 console.log(err);
66}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
45
var assert = require('assert');
const longestPalindrome = (str) => {
// fill in
return '';
};
try {
assert.equal(longestPalindrome(''), '');
console.log('PASSED: ' + "`longestPalindrome('')` should return `''`");
} catch (err) {
console.log(err);
}
try {
assert.equal(longestPalindrome('algodaily'), 'a');
console.log(
'PASSED: ' + "`longestPalindrome('algodaily')` should return `'a'`"
);
} catch (err) {
console.log(err);
}
try {
assert.equal(longestPalindrome('gymmyg'), 'gymmyg');
OUTPUT
Results will appear here.