Skip to content

Commit ba7fd2e

Browse files
committed
added solution 5 with it's test case
1 parent 25a08ff commit ba7fd2e

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/solutions/5/index.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import LongestPalindromicSubstring from './longestPalindrome';
2+
3+
const run = () => {
4+
const input = 'babad';
5+
console.log("Input: ", input);
6+
7+
console.time('longestPalindrome');
8+
console.log("Output: ", LongestPalindromicSubstring(input));
9+
console.timeEnd('longestPalindrome');
10+
}
11+
12+
export default run;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import longestPalindrome from "./longestPalindrome";
2+
3+
test('Solution 5 - Longest Palindrome', () => {
4+
expect(longestPalindrome('babad')).toBe('bab');
5+
expect(longestPalindrome('cbbd')).toBe('bb');
6+
expect(longestPalindrome('a')).toBe('a');
7+
expect(longestPalindrome('abcdefgfedcba')).toBe('abcdefgfedcba');
8+
})

src/solutions/5/longestPalindrome.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const longestPalindrome = (s: string): string => {
2+
let max = 0;
3+
let res = '';
4+
for (let i = 0; i < s.length; i++) {
5+
for (let j = i + 1; j <= s.length; j++) {
6+
if (s.slice(i, j).length > max && isPalindrome(s.slice(i, j))) {
7+
max = s.slice(i, j).length;
8+
res = s.slice(i, j);
9+
}
10+
}
11+
}
12+
return res;
13+
};
14+
15+
const isPalindrome = (s: string): boolean => {
16+
let i = 0;
17+
let j = s.length - 1;
18+
while (i < j) {
19+
if (s[i] !== s[j]) {
20+
return false;
21+
}
22+
i++;
23+
j--;
24+
}
25+
return true;
26+
};
27+
28+
export default longestPalindrome;

0 commit comments

Comments
 (0)