8. Longest palindromic substring in a String

8. Longest palindromic substring in a String


Problem link :- click here


package programs;

public class String__8
{

	/*
		Longest palindrome in a string
				s = "aaaaabbaa"		ouput -->  aabbaa
				s = "abc"				ouput -->  a
		
		If we try it in brute force method it will be O( |s|^3 )
		|s|^2 to take the sub-String     and  |s|  to check is it palindrome
		
		there is a better option that is taking sub-String in just |s|
		
		to cover all the possible sub-array we have to take
		all possible sub-String by taking that element as center
		
		the sub-Strings taken above are only odd palinsromic sub-Strings
		there are also even palindromic sub-arrays, we shoould also 
		consider these sub-Strings 
		
		we must update the longest palindromic sub-String in both 
		the steps above
	*/
	
	static String longestPalindromicSubString(String s)
	{
		String long_str = new String();       //output
		
		//we will start from second element because you will not get 
		//any substring with first element as center (except itself)
		for(int i=1; i<s.length(); i++)
		{
			//odd palindromic substring
			int low = i;		//equal to 'i' because 
			int high = i;    	//every single character is also a palindrome
			
			while(   (  low >=0   &&    high < s.length()   )      &&   
				     (  s.charAt(low)  ==  s.charAt(high)  )                )
			{
				//updating long_str 
				if(   (high-low+1)  > long_str.length() )
					long_str = s.substring(low, high+1);
				
				low--;
				high++;
			}
			
			
			//even palindromic substring
			low = i-1;
			high = i;
			
			while(  (  low>=0    &&     high<s.length()   )    &&
				     ( s.charAt(low)  ==  s.charAt(high)  )               )
			{
				//updating long_str
				if( (high-low+1) > long_str.length() )
					long_str = s.substring(low, high+1);
				
				low--;
				high++;
			}
		}
		
		return long_str;
	}
	
	public static void main(String[] args)
	{
		String s = "aaaabbaa";
		String str = longestPalindromicSubString(s);
		System.out.println(str);
	}

}

Time complexity :-O()
Space complexity :- O()

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree