Problem:
Given a string s
, return the longest
palindromic
substring in s
.
Example 1:
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters.
Solution:
Simple solution for beginners with separate function to check palindrome and code to create all possible substrings from a string.
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
let allsubstring = new Array();
let longestpalindrome = "";
for(let i = 0; i < s.length;i++){
for(let j = i+1; j < s.length +1 ;j++){
allsubstring.push(s.slice(i,j));
}
}
for(let i = 0; i < allsubstring.length; i++){
if(ispalindrome(allsubstring[i])){
if(longestpalindrome.length < allsubstring[i].length){
longestpalindrome = allsubstring[i];
}
}
}
return longestpalindrome;
};
function ispalindrome(string){
if(string.length > 2){
for(let i = 0; i < Math.floor(string.length/2) ; i++){
if(string[i] != string[string.length -i -1]){
return false;
}
}
}
else{
if(string[1]){
if(string[1] != string[0]){
return false;
}
}
}
return true;
}
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.