Open In App

Length of the longest substring that do not contain any palindrome

Last Updated : 18 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string of lowercase, find the length of the longest substring that does not contain any palindrome as a substring.

Examples:

Input : str = "daiict" 
Output : 3
dai, ict are longest substring that do not contain any 
palindrome as substring

Input : str = "a"
Output : 0
a is itself a palindrome 

The idea is to observe that if any character forms a palindrome, it can not be included in any substring. So, in that case, the required substring will be picked from before or after that character which forms a palindrome. 
Therefore, a simple solution is to traverse the string and, for each character, check whether it forms a palindrome of length 2 or 3 with its adjacent characters. If it does not, then increase the length of the substring, otherwise re-initialize the length of the substring to zero. Using this approach, find the length of the maximum substring.

Below is the implementation of the above approach:

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length of the longest
// substring
int lenoflongestnonpalindrome(string s)
{
    // initializing the variables
    int max1 = 1, len = 0;
 
    for (int i = 0; i < s.length() - 1; i++) {
        // checking palindrome of size 2
        // example: aa
        if (s[i] == s[i + 1])
            len = 0;
        // checking palindrome of size 3
        // example: aba
        else if (s[i + 1] == s[i - 1] && i > 0)
            len = 1;
        else // incrementing length of substring
            len++;
        max1 = max(max1, len + 1); // finding maximum
    }
 
    // if there exists single character then
    // it is always palindrome
    if (max1 == 1)
        return 0;
    else
        return max1;
}
 
// Driver Code
int main()
{
    string s = "synapse";
    cout << lenoflongestnonpalindrome(s) << "\n";
    return 0;
}


Java




// Java implementation of the above approach
import java.util.Arrays;
import java.lang.Math;
 
class GFG {
 
    // Function to find the length of the longest
    // substring
    public static int lenoflongestnonpalindrome(String s)
    {
        // initializing the variables
        int max1 = 1, len = 0;
        char[] new_str = s.toCharArray();
 
        for (int i = 0; i < new_str.length - 1; i++) {
            // checking palindrome of size 2
            // example: aa
            if (new_str[i] == new_str[i + 1])
                len = 0;
            // checking palindrome of size 3
            // example: aba
            else if (i > 0 && (new_str[i + 1] == new_str[i - 1]))
                len = 1;
            else // incrementing length of substring
                len++;
            max1 = Math.max(max1, len + 1); // finding maximum
        }
 
        // if there exits single character then
        // it is always palindrome
        if (max1 == 1)
            return 0;
        else
            return max1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "synapse";
        System.out.println(lenoflongestnonpalindrome(s));
    }
}
 
// This code is contributed by princiraj1992


Python3




# Python3 implementation of the above approach
 
# Function to find the length
# of the longest substring
def lenoflongestnonpalindrome(s):
 
    # initializing the variables
    max1, length = 1, 0
 
    for i in range(0, len(s) - 1):
         
        # checking palindrome of
        # size 2 example: aa
        if s[i] == s[i + 1]:
            length = 0
             
        # checking palindrome of
        # size 3 example: aba
        elif s[i + 1] == s[i - 1] and i > 0:
            length = 1
        else: # incrementing length of substring
            length += 1
        max1 = max(max1, length + 1) # finding maximum
 
    # If there exits single character
    # then it is always palindrome
    if max1 == 1:
        return 0
    else:
        return max1
 
# Driver Code
if __name__ == "__main__":
 
    s = "synapse"
    print(lenoflongestnonpalindrome(s))
     
# This code is contributed by Rituraj Jain


C#




// C# implementation of the above approach
using System;
     
class GFG
{
 
    // Function to find the length of the longest
    // substring
    public static int lenoflongestnonpalindrome(String s)
    {
        // initializing the variables
        int max1 = 1, len = 0;
        char[] new_str = s.ToCharArray();
 
        for (int i = 0; i < new_str.Length - 1; i++)
        {
            // checking palindrome of size 2
            // example: aa
            if (new_str[i] == new_str[i + 1])
                len = 0;
                 
            // checking palindrome of size 3
            // example: aba
            else if (i > 0 && (new_str[i + 1] == new_str[i - 1]))
                len = 1;
            else // incrementing length of substring
                len++;
            max1 = Math.Max(max1, len + 1); // finding maximum
        }
 
        // if there exits single character then
        // it is always palindrome
        if (max1 == 1)
            return 0;
        else
            return max1;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "synapse";
        Console.WriteLine(lenoflongestnonpalindrome(s));
    }
}
 
// This code has been contributed by 29AjayKumar


PHP




<?php
// PHP implementation of the above approach
 
// Function to find the length of the longest
// substring
function lenoflongestnonpalindrome($s)
{
    // initializing the variables
    $max1 = 1; $len = 0;
 
    for ($i = 0; $i < strlen($s) - 1; $i++)
    {
        // checking palindrome of size 2
        // example: aa
        if ($s[$i] == $s[$i + 1])
            $len = 0;
             
        // checking palindrome of size 3
        // example: aba
        else if ($s[$i + 1] == $s[$i - 1] && $i > 0)
            $len = 1;
        else // incrementing length of substring
            $len++;
        $max1 = max($max1, $len + 1); // finding maximum
    }
 
    // if there exits single character then
    // it is always palindrome
    if ($max1 == 1)
        return 0;
    else
        return $max1;
}
 
// Driver Code
$s = "synapse";
echo lenoflongestnonpalindrome($s), "\n";
 
// This code is contributed by AnkitRai01
 
?>


Javascript




<script>
 
// JavaScript implementation of the above approach
 
// Function to find the length of the longest
// substring
function lenoflongestnonpalindrome(s)
{
    // initializing the variables
    let max1 = 1, len = 0;
 
    for (let i = 0; i < s.length - 1; i++) {
        // checking palindrome of size 2
        // example: aa
        if (s[i] == s[i + 1])
            len = 0;
        // checking palindrome of size 3
        // example: aba
        else if (s[i + 1] == s[i - 1] && i > 0)
            len = 1;
        else // incrementing length of substring
            len++;
        max1 = Math.max(max1, len + 1); // finding maximum
    }
 
    // if there exits single character then
    // it is always palindrome
    if (max1 == 1)
        return 0;
    else
        return max1;
}
 
// Driver Code
 
    let s = "synapse";
    document.write(lenoflongestnonpalindrome(s) + "<br>");
     
 
//This code is contributed by Manoj
</script>


Output: 

7

 

Time complexity: O(n) where n is length of input string

Auxiliary Space: O(1)



Similar Reads

Length of the longest substring that does not contain any vowel
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring that does not contain any vowel. Examples: Input: S = “geeksforgeeks”Output: 3The substring "ksf" is the longest substring that does not contain any vowel. The length of this substring is 3. Input: S = “ceebbaceeffo”Output: 2 Naive Approac
6 min read
Lexicographically smallest string of maximum length made up of first K alphabets that does not contain any repeating substring
Given a positive integer K, the task is to find lexicographically the smallest string that can be generated by using the first K lowercase alphabets such that no substring of length at least 2 is repeated in the generated string. Examples: Input: K = 3Output: aabacbbccaExplanation:In the string "aabacbbcca", all possible substrings of length at lea
5 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Length of the longest increasing subsequence which does not contain a given sequence as Subarray
Given two arrays arr[] and arr1[] of lengths N and M respectively, the task is to find the longest increasing subsequence of array arr[] such that it does not contain array arr1[] as subarray. Examples: Input: arr[] = {5, 3, 9, 3, 4, 7}, arr1[] = {3, 3, 7}Output: 4Explanation: Required longest increasing subsequence is {3, 3, 4, 7}. Input: arr[] =
14 min read
Largest number not exceeding N that does not contain any of the digits of S
Given a numberic string N (1 ≤ |N| ≤ 105) and another numeric string S (1 ≤ |S| ≤ 105), the task is to find the maximum number ≤ N such that it doesn't contain digits of string S. Remove leading zeros, if required. Note: The string S doesn't contain '0'. Examples: Input: N = "2004", S = "2" Output: 1999 Explanation: 2004 has digit 2 which is in the
14 min read
Length of Longest Palindrome Substring
Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string "aa" is the longest substring that is a palindrom
20 min read
Check if there exists a permutation of given string which doesn't contain any monotonous substring
Given a string S of lowercase English alphabets, the task is to check if there exists an arrangement of string S such that it doesn't contain any monotonous substring. A monotonous substring has the following properties: Length of such substring is 2.Both the characters are consecutive, For example - "ab", "cd", "dc", "zy" etc. Examples: Input: S =
7 min read
Next word that does not contain a palindrome and has characters from first k
Given a string and a limit k, find lexicographically next word which contains characters from a set of first K letters of the English alphabet and does not contain a palindrome as it's substring of length more than one. It may be assumed that the input string does not contain a palindromic substring. Examples: Input : s = "cba" k = 4 Output : cbd I
7 min read
DFA that begins with 'a' but does not contain substring 'aab'
Prerequisite: Introduction to Deterministic Finite Automata Construct a DFA that accepts string str starting with input alphabet 'a' but does not contain 'aab' as a substring over input {a, b}. Examples: Input: str = "babba" Output: Not Accepted Explanation: The given string doesn't start with 'a'. Input: str = "abbaaaaa" Output: Accepted Explanati
10 min read
Find a Symmetric matrix of order N that contain integers from 0 to N-1 and main diagonal should contain only 0's
Given an integer N. The task is to generate a symmetric matrix of order N*N having the following properties. Main diagonal should contain only 0'sThe matrix should contain elements from 0 to N-1 only. Examples: Input: N = 4 Output: 0 2 3 1 2 0 1 3 3 1 0 2 1 3 2 0Input: N = 5 Output: 0 2 3 4 1 2 0 4 1 3 3 4 0 2 1 4 1 2 0 3 1 3 1 3 0 Approach: Since
10 min read
Article Tags :
Practice Tags :