Skip to content

Instantly share code, notes, and snippets.

@ahmadalibaloch
Created November 29, 2019 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadalibaloch/3959cb6a45ec0b1fe811f750a56f3652 to your computer and use it in GitHub Desktop.
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)
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