📜  最短回文子串

📅  最后修改于: 2021-09-03 14:55:21             🧑  作者: Mango

给定一个字符串,您需要找到该字符串的最短回文子字符串。如果有多个答案输出字典序最小的。

例子:

Input: zyzz
Output:y

Input: abab
Output: a

天真的方法:

  • 该方法类似于寻找最长的回文子串。我们跟踪偶数和奇数长度的子串并将其存储在向量中。
  • 之后,我们将对向量进行排序并打印字典序最小的子串。这也可能包括空子串,但我们需要忽略它们。

下面是上述方法的实现:

C++
// C++ program to find the shortest
// palindromic substring
#include 
using namespace std;
 
// Function return the shortest
// palindromic substring
string ShortestPalindrome(string s)
{
    int n = s.length();
     
    vector v;
     
    // One by one consider every character 
    // as center point of even and length
    // palindromes
    for (int i = 0; i < n; i++)
    {
        int l = i;
        int r = i;
        string ans1 = "";
        string ans2 = "";
         
        // Find the longest odd length palindrome
        // with center point as i
        while (l >= 0 && r < n && s[l] == s[r])
        {
            ans1 += s[l];
            l--;
            r++;
        }
        l = i - 1;
        r = i;
         
        // Find the even length palindrome 
        // with center points as i-1 and i.
        while (l >= 0 && r < n && s[l] == s[r])
        {
            ans2 += s[l];
            l--;
            r++;
        }
        v.push_back(ans1);
        v.push_back(ans2);
    }
    string ans = v[0];
     
    // Smallest substring which is
    // not empty
    for (int i = 0; i < v.size(); i++)
    {
        if (v[i] != "")
        {
            ans = min(ans, v[i]);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
     
    cout << ShortestPalindrome(s);
     
    return 0;
}


Java
// Java program to find the shortest
// palindromic substring
import java.util.*;
import java.io.*;
 
class GFG{
 
// Function return the shortest
// palindromic substring
public static String ShortestPalindrome(String s)
{
    int n = s.length();
    Vector v = new Vector();
     
    // One by one consider every character 
    // as center point of even and length
    // palindromes
    for(int i = 0; i < n; i++)
    {
        int l = i;
        int r = i;
        String ans1 = "";
        String ans2 = "";
         
        // Find the longest odd length palindrome
        // with center point as i    
        while (l >= 0 && r < n &&
          s.charAt(l) == s.charAt(r))
        {
            ans1 += s.charAt(l);
            l--;
            r++;
        }
        l = i - 1;
        r = i;
         
        // Find the even length palindrome 
        // with center points as i-1 and i.
        while (l >= 0 && r < n &&
          s.charAt(l) == s.charAt(r))
        {
            ans2 += s.charAt(l);
            l--;
            r++;
        }
         
        v.add(ans1);
        v.add(ans2);
    }
     
    String ans = v.get(0);
     
    // Smallest substring which is
    // not empty
    for(int i = 0; i < v.size(); i++)
    {
        if (v.get(i) != "")
        {
            if (ans.charAt(0) >=
                v.get(i).charAt(0))
            {
                ans = v.get(i);
            }
        }
    }
    return ans;
}
 
// Driver code
public static void main(String []args)
{
    String s = "geeksforgeeks";
     
    System.out.println(ShortestPalindrome(s));
}
}
 
// This code is contributed by rag2127


Python3
# Python3 program to find the shortest
# palindromic substring
 
# Function return the shortest
# palindromic substring
def ShortestPalindrome(s) :
 
    n = len(s)
     
    v = []
     
    # One by one consider every character
    # as center point of even and length
    # palindromes
    for i in range(n) :
     
        l = i
        r = i
        ans1 = ""
        ans2 = ""
         
        # Find the longest odd length palindrome
        # with center point as i
        while ((l >= 0) and (r < n) and (s[l] == s[r])) :
         
            ans1 += s[l]
            l -= 1
            r += 1
 
        l = i - 1
        r = i
         
        # Find the even length palindrome
        # with center points as i-1 and i.
        while ((l >= 0) and (r < n) and (s[l] == s[r])) :
         
            ans2 += s[l]
            l -= 1
            r += 1
 
        v.append(ans1)
        v.append(ans2)
     
    ans = v[0]
     
    # Smallest substring which is
    # not empty
    for i in range(len(v)) :
     
        if (v[i] != "") :
         
            ans = min(ans, v[i])
 
    return ans
     
 
s = "geeksforgeeks"
 
print(ShortestPalindrome(s))
 
# This code is contributed by divyesh072019


C#
// C# program to find the shortest
// palindromic substring
using System;
using System.Collections.Generic;
class GFG
{
   
  // Function return the shortest
  // palindromic substring
  static string ShortestPalindrome(string s)
  {
    int n = s.Length;
    List v = new List();
     
    // One by one consider every character 
    // as center point of even and length
    // palindromes   
    for(int i = 0; i < n; i++)
    {
      int l = i;
      int r = i;
      string ans1 = "";
      string ans2 = "";
       
      // Find the longest odd length palindrome
      // with center point as i       
      while(l >= 0 && r < n && s[l] == s[r])
      {
        ans1 += s[l];
        l--;
        r++;
      }
      l = i - 1;
      r = i;
 
      // Find the even length palindrome 
      // with center points as i-1 and i.
      while(l >= 0 && r < n && s[l] == s[r])
      {
        ans2 += s[l];
        l--;
        r++;
      }
      v.Add(ans1);
      v.Add(ans2);
    }
    string ans = v[0];
 
    // Smallest substring which is
    // not empty
    for(int i = 0; i < v.Count; i++)
    {
      if(v[i] != "")
      {
        if(ans[0] >= v[i][0])
        {
          ans = v[i];
        }
      }
    }
    return ans;
  }
   
  // Driver code
  static public void Main ()
  {
    string s = "geeksforgeeks";
    Console.WriteLine(ShortestPalindrome(s));
  }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


C++
// C++ program to find the shortest
// palindromic substring
#include 
using namespace std;
 
// Function return the shortest
// palindromic substring
char ShortestPalindrome(string s)
{
    int n = s.length();
    char ans = s[0];
     
    // Finding the smallest character
    // present in the string
    for(int i = 1; i < n ; i++)
    {
        ans = min(ans, s[i]);
    }
     
    return ans;
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
     
    cout << ShortestPalindrome(s);
     
    return 0;
}


Java
// Java program to find the shortest
// palindromic subString
 
class GFG{
 
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
    int n = s.length();
    char ans = s.charAt(0);
     
    // Finding the smallest character
    // present in the String
    for(int i = 1; i < n; i++)
    {
        ans = (char) Math.min(ans, s.charAt(i));
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "geeksforgeeks";
    System.out.print(ShortestPalindrome(s));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program to find the shortest
# palindromic substring
 
# Function return the shortest
# palindromic substring
def ShortestPalindrome(s):
 
    n = len(s)
    ans = s[0]
       
    # Finding the smallest character
    # present in the string
    for i in range(1, n):
        ans = min(ans, s[i])
 
    return ans
 
# Driver code
s = "geeksforgeeks"
       
print(ShortestPalindrome(s))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program to find the shortest
// palindromic subString
using System;
 
class GFG{
 
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
    int n = s.Length;
    char ans = s[0];
     
    // Finding the smallest character
    // present in the String
    for(int i = 1; i < n; i++)
    {
        ans = (char) Math.Min(ans, s[i]);
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "geeksforgeeks";
    Console.Write(ShortestPalindrome(s));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

e

时间复杂度: O(N^2),其中 N 是字符串的长度。

有效的方法:

  • 这里的观察是单个字符也是回文。因此,我们只需要打印字符串出现的字典序最小的字符。

下面是上述方法的实现:

C++

// C++ program to find the shortest
// palindromic substring
#include 
using namespace std;
 
// Function return the shortest
// palindromic substring
char ShortestPalindrome(string s)
{
    int n = s.length();
    char ans = s[0];
     
    // Finding the smallest character
    // present in the string
    for(int i = 1; i < n ; i++)
    {
        ans = min(ans, s[i]);
    }
     
    return ans;
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
     
    cout << ShortestPalindrome(s);
     
    return 0;
}

Java

// Java program to find the shortest
// palindromic subString
 
class GFG{
 
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
    int n = s.length();
    char ans = s.charAt(0);
     
    // Finding the smallest character
    // present in the String
    for(int i = 1; i < n; i++)
    {
        ans = (char) Math.min(ans, s.charAt(i));
    }
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "geeksforgeeks";
    System.out.print(ShortestPalindrome(s));
}
}
 
// This code is contributed by Rajput-Ji

蟒蛇3

# Python3 program to find the shortest
# palindromic substring
 
# Function return the shortest
# palindromic substring
def ShortestPalindrome(s):
 
    n = len(s)
    ans = s[0]
       
    # Finding the smallest character
    # present in the string
    for i in range(1, n):
        ans = min(ans, s[i])
 
    return ans
 
# Driver code
s = "geeksforgeeks"
       
print(ShortestPalindrome(s))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program to find the shortest
// palindromic subString
using System;
 
class GFG{
 
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
    int n = s.Length;
    char ans = s[0];
     
    // Finding the smallest character
    // present in the String
    for(int i = 1; i < n; i++)
    {
        ans = (char) Math.Min(ans, s[i]);
    }
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "geeksforgeeks";
    Console.Write(ShortestPalindrome(s));
}
}
 
// This code is contributed by 29AjayKumar

Javascript


输出:
e

时间复杂度: O(N),其中 N 是字符串的长度。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live