Given a string ’S’ consisting of lower case English letters, you are supposed to return the longest palindromic substring of ‘S’.
Note that in case of more than one longest palindromic substrings with the same length you need to return the rightmost substring in the given string. For example in string “bbbab”, there are two possible longest palindromic substrings i.e. “bbb” and “bab”, and since you are supposed to return the rightmost substring, so you need to return “bab” as the answer.
Note:
A substring is a contiguous sequence of elements within a string (for example, “bcd” is a substring of “abcde” while “bce” is not).
A string is said to be palindrome if the reverse of the string is the same as the actual string. For example, “abba” is a palindrome, but “abbc” is not a palindrome.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The only line of each test case contains a single string ‘S’ consisting of only lowercase English letters.
Output Format:
For each test case, print a single string in a single line denoting the longest palindromic substring of string ‘S’.
The output for each test case is in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 100
Where ‘N’ is the length of the string.
Time limit: 1 sec
Approach :
1) Create a 2-D dp boolean vector(with all false initially) where dp[i][j] states whether s[i...j] is a palindrome or not and initilialise a variable ans=1 which will store the final answer....read more
The brute force solution is to pick all possible starting and ending positions for a substring and verify if it is a palindrome.
The steps are as follows:
- If the length of the given string ...read more
To improve our brute force solution, we first observe how we can avoid unnecessary re-computation while we are validating if a substring is a palindrome or not. Consider the case "x...read more
When you observe closely you will realise that a palindrome has mirrors around its centre, a palindrome can be expanded in both directions from its centre.
The steps are as fol...read more
Top Nagarro Software Developer interview questions & answers
Popular interview questions of Software Developer
Reviews
Interviews
Salaries
Users/Month