Created
November 29, 2019 08:08
-
-
Save ahmadalibaloch/3959cb6a45ec0b1fe811f750a56f3652 to your computer and use it in GitHub Desktop.
Finding longest palindrome (symmetric) substring in a string using Javascript (brute-force method)
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
function longest_symm_substr(s) { | |
let longest_symmetric = ''; | |
for(let i=0;i<s.length-1;i++){ | |
// this loop will each time get a new substring incrementing the index from 0 to length | |
let curr_str = s.substring(i); | |
for(let j=curr_str.length-1;j>0;j--){ | |
// this loop will find all possible symmetric substrings in the above indexed substring | |
let str = curr_str.substring(0,j) | |
if(str === str.split('').reverse().join('')){ | |
if(longest_symmetric.length < str.length){ | |
// keep record of the longest one | |
longest_symmetric = str; | |
} | |
} | |
} | |
} | |
return longest_symmetric; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment