Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to find longest palindrome substring in C++

1 Answer

0 votes
#include <iostream>

int longestPalindromeSubstring(std::string str) {
    int len = str.size();
    int longestLength = 1, start = 0;
  
    for (int i = 0; i < len; i++) {
        for (int j = i; j < len; j++) {
            int palindrome = 1;
  
            for (int k = 0; k < (j - i + 1) / 2; k++) {
                if (str[i + k] != str[j - k]) {
                    palindrome = 0;
                }
            }
  
            if (palindrome && (j - i + 1) > longestLength) {
                start = i;
                longestLength = j - i + 1;
            }
        }
    }
  
    std::cout << "Longest palindrome substring = ";
    for (int i = start; i <= start + longestLength - 1; i++)
        std::cout << str[i];
    std::cout << "\n";
  
    return longestLength;
}
  
int main()
{
    std::string str = "qabcbaproggorpxyyxzv";
    
    int result = longestPalindromeSubstring(str);
     
    std::cout << "Length palindrome substring length = " << result;
}
 
 
 
 
/*
run:
 
Longest palindrome substring = proggorp
Length palindrome substring length = 8
 
*/

 





answered Jun 3, 2023 by avibootz

Related questions

2 answers 45 views
1 answer 35 views
1 answer 35 views
1 answer 32 views
1 answer 29 views
...