Lexicographically all Shortest Palindromic Substrings from a given string
Given a string s of size N. The task is to find lexicographically all the shortest palindromic substrings from the given string.
Examples:
Input: s= “programming”
Output: a g i m n o p r
Explanation:
The Lexicographical shortest palindrome substring for the word “programming” will be the single characters from the given string. Hence, the output is : a g i m n o p r.
Input: s= “geeksforgeeks”
Output: e f g k o r s
Approach:
To solve the problem mentioned above, the very first observation is that the shortest palindromic substring will be of size 1. So, as per the problem statement, we have to find all distinct substrings of size 1 lexicographically, which means all the characters in the given string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void shortestPalindrome(string s)
{
int abcd[26] = { 0 };
for ( int i = 0; i < s.length(); i++)
abcd[s[i] - 97] = 1;
for ( int i = 0; i < 26; i++) {
if (abcd[i] == 1)
cout << char (i + 97) << " " ;
}
}
int main()
{
string s = "geeksforgeeks" ;
shortestPalindrome(s);
return 0;
}
|
Java
class Main
{
static void shortestPalindrome(String s)
{
int [] abcd = new int [ 26 ];
for ( int i = 0 ; i < s.length(); i++)
abcd[s.charAt(i) - 97 ] = 1 ;
for ( int i = 0 ; i < 26 ; i++)
{
if (abcd[i] == 1 )
{
System.out.print(( char )(i + 97 ) + " " );
}
}
}
public static void main(String[] args)
{
String s = "geeksforgeeks" ;
shortestPalindrome(s);
}
}
|
Python3
def shortestPalindrome (s) :
abcd = [ 0 ] * 26
for i in range ( len (s)):
abcd[ ord (s[i]) - 97 ] = 1
for i in range ( 26 ):
if abcd[i] = = 1 :
print ( chr (i + 97 ), end = ' ' )
s = "geeksforgeeks"
shortestPalindrome (s)
|
C#
using System;
class GFG{
static void shortestPalindrome( string s)
{
int [] abcd = new int [26];
for ( int i = 0; i < s.Length; i++)
abcd[s[i] - 97] = 1;
for ( int i = 0; i < 26; i++)
{
if (abcd[i] == 1)
{
Console.Write(( char )(i + 97) + " " );
}
}
}
static public void Main( string [] args)
{
string s = "geeksforgeeks" ;
shortestPalindrome(s);
}
}
|
Javascript
<script>
function shortestPalindrome(s)
{
let abcd = Array.from({length: 26}, (_, i) => 0);
for (let i = 0; i < s.length; i++)
abcd[s[i].charCodeAt() - 97] = 1;
for (let i = 0; i < 26; i++)
{
if (abcd[i] == 1)
{
document.write(String.fromCharCode(i + 97) + " " );
}
}
}
let s = "geeksforgeeks" ;
shortestPalindrome(s.split( '' ));
</script>
|
Time Complexity: O(N), where N is the size of the string.
Space Complexity: O(1)
Last Updated :
07 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...