forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Longest Palindromic Substring [JavaScript] (iiitv#412)
* Added LongestPalindromicSubsequence [JavaScript] * Added LongestPalindromicSubsequence [JavaScript] * Added LongestPalindromicSubsequence [JavaScript] * Bot fix v1.0 * Bot fix v1.1 * Splitting some lines :O * Bleh
- Loading branch information
Showing
2 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
longest_palindromic_substring/longestPalindromicSubstring.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
function expandAroundCenter (test, left, right) { | ||
/* | ||
:param test: Input string whose substrings are to be checked | ||
:param left: Left end of result palindromic substring | ||
:param right: Right end of result palindromic substring | ||
:return: Length of palindromic substring | ||
*/ | ||
let n = test.length; | ||
while (left >= 0 && right < n && test.charAt(left) === test.charAt(right)) { | ||
left--; | ||
right++; | ||
} | ||
return right - left - 1; | ||
} | ||
|
||
function longestPalindromicSubstring (test) { | ||
/* | ||
Function to find longest substring which is a palindrome | ||
:param test: Input string whose substrings are to be checked | ||
:return: Longest substring of input string which is a palindrome | ||
Time complexity: O(n^2) | ||
Space complexity: O(1) | ||
*/ | ||
let start = 0; | ||
let end = 0; | ||
|
||
for (let i = 0; i < test.length; i++) { | ||
let length = Math.max(expandAroundCenter(test, i, i), | ||
expandAroundCenter(test, i, i + 1)); | ||
if (length > end - start) { | ||
start = i - Math.floor((length - 1) / 2); | ||
end = i + Math.floor(length / 2); | ||
} | ||
} | ||
return test.slice(start, end + 1); | ||
} | ||
|
||
function main () { | ||
let test = 'geeksforgeeks'; | ||
console.log('Longest Palindromic Substring of', | ||
test, 'is', longestPalindromicSubstring(test)); | ||
} | ||
|
||
main(); |