Brute way to solve longest palindrome substring question

Brute way to solve longest palindrome substring question

Table of contents

No heading

No headings in the article.

The longest palindrome substring is an interesting question in computer science.Many people solve it in different ways. Today I will introduce the most direct way, the brute force solution to handle this problem.Actually, I wan to write it in javascript.

Firstly, we need to know what is the meaning of "palindrome".As ChatGPT said:

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. In other words, a palindrome is a string of characters that is spelled the same way in both directions.

For example, "racecar" is a palindrome because it is spelled the same way backward as forward. Another example is the phrase "A man, a plan, a canal, Panama!" which is a palindrome when spaces and punctuation are ignored.

Palindromes can be found in various languages and can be formed by words, phrases, and even sentences. Palindromes are often used in puzzles, word games, and literature, and can be an interesting topic for linguists and computer scientists who study language and pattern recognition.

So we can start from each character to find the longest palindrome substring.We can define a separate function named isPalindrome, the code as below:

const isPalindrome = (s) => {
    if (s.length <= 1) return true;

    for (let i = 0; i < Math.floor(s.length/2); i++) {
        if (s[i] != s[s.length - i - 1]) return false;
    }

    return true;
}

Then we write the main code to use it:

const longestPalindrome = (s) => {
    if (s.length === 0) return '';
    let res = [];
    for (let i = 0; i < s.length; i++) {
        for (let j = i + 1; j <= s.length; j++) {
            if (isPalindrome(s.substring(i, j))) res.push(s.substring(i, j));
        }
    }

    let longestSubString = '';

    res.forEach((item) => {
        if (item.length > longestSubString.length) longestSubString = item;
    });

    return longestSubString;
}

Its time complexity is O(n^3), so it is not a good algorithm.I will introduce a better algorithm in the next blog.