Answers for "find longest palindrome substring"

1

find all the palindrome substring in a given string

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

// expand in both directions of low and high to find all palindromes
void expand(string str, int low, int high, auto &set)
{
	// run till str[low.high] is a palindrome
	while (low >= 0 && high < str.length()
			&& str[low] == str[high])
	{
		// push all palindromes into the set
		set.insert(str.substr(low, high - low + 1));

		// expand in both directions
		low--, high++;
	}
}

// Function to find all unique palindromic substrings of given string
void allPalindromicSubstrings(string str)
{
	// create an empty set to store all unique palindromic substrings
	unordered_set<string> set;

	for (int i = 0; i < str.length(); i++)
	{
		// find all odd length palindrome with str[i] as mid point
		expand(str, i, i, set);

		// find all even length palindrome with str[i] and str[i+1] as
		// its mid points
		expand(str, i, i + 1, set);
	}

	// print all unique palindromic substrings
	for (auto i : set)
		cout << i << " ";
}

int main()
{
	string str = "google";

	allPalindromicSubstrings(str);

	return 0;
}
Posted by: Guest on May-29-2020
0

Longest length of palindromic sum substring

// Longest length of palindromic sum substring
fn longest_palindrome(s: String) -> usize {
    let size = s.len();
    if size == 0 {
        return 0;
    }
    let mut flags = vec![vec![false; size]; size];
    let mut start = 0;
    let mut max = 1;
    let b = s.as_bytes();
    for i in 0..size {
        flags[i][i] = true;
        for j in 0..i {
            flags[j][i] = b[j] == b[i] && (i-j < 3 || flags[j+1][i-1]);
            if flags[j][i] && i - j + 1 > max {
                start = j;
                max = i - j + 1;
            }
        }
    }
    let end = start + max;
    return ((s[start as usize..end as usize]).to_string()).len();
}

fn main() {
    let text = String::from("the quick brown fox haaa");  // 3
    println!("Length of longest palindrome = {} ", longest_palindrome(text)); 
}
Posted by: Guest on August-16-2021

Code answers related to "find longest palindrome substring"

Browse Popular Code Answers by Language