📌  相关文章
📜  每个索引的最大长度回文子串,使其在该索引处开始和结束

📅  最后修改于: 2021-04-17 17:39:58             🧑  作者: Mango

给定一个字符串S,该字符串的各项指标任务是找到最长回文串的长度是该指数在任开始结束

例子:

方法:解决此问题的想法是遍历字符串,并针对每个索引,检查可以用该索引作为回文子字符串的起始索引结束索引形成的最长回文子字符串。请按照以下步骤解决问题:

  • 初始化数组palLength []以存储每个索引的最长回文子字符串的长度。
  • 使用变量i遍历字符串并执行以下操作:
    • 初始化一个变量,例如maxLength ,以存储每个索引的最长回文子字符串的长度。
    • i视为回文子串的结尾索引,并从[0,i – 1]范围内的j中找到第一个索引,使得S [j,i]是回文。更新maxLength
    • 将i作为回文子串的起始索引,并从[N – 1,i + 1]范围内的j中找到最后一个索引,以使S [i,j]为回文。更新maxLength
    • 存储通过将maxLength的值存储在palLength [i]中获得的最大长度
  • 完成上述步骤后,将结果打印为palLength []

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to return true if
// S[i...j] is a palindrome
bool isPalindrome(string S, int i, int j)
{
 
  // Iterate until i < j
  while (i < j)
  {
 
    // If unequal character encountered
    if (S[i] != S[j])
      return false;
    i++;
    j--;
  }
 
  // Otherwise
  return true;
}
 
// Function to find for every index,
// longest palindromic substrings
// starting or ending at that index
void printLongestPalindrome(string S, int N)
{
 
  // Stores the maximum palindromic
  // substring length for each index
  int palLength[N];
 
  // Traverse the string
  for (int i = 0; i < N; i++)
  {
 
    // Stores the maximum length
    // of palindromic substring
    int maxlength = 1;
 
    // Consider that palindromic
    // substring ends at index i
    for (int j = 0; j < i; j++)
    {
 
      // If current character is
      // a valid starting index
      if (S[j] == S[i])
      {
 
        // If S[i, j] is palindrome,
        if (isPalindrome(S, j, i))
        {
 
          // Update the length of
          // the longest palindrome
          maxlength = i - j + 1;
          break;
        }
      }
    }
 
    // Consider that palindromic
    // substring starts at index i
    for (int j = N - 1; j > i; j--)
    {
 
      // If current character is
      // a valid ending index
      if (S[j] == S[i])
      {
 
        // If str[i, j] is palindrome
        if (isPalindrome(S, i, j))
        {
 
          // Update the length of
          // the longest palindrome
          maxlength = max(j - i + 1, maxlength);
          break;
        }
      }
    }
 
    // Update length of the longest
    // palindromic substring for index i
    palLength[i] = maxlength;
  }
 
  // Print the length of the
  // longest palindromic substring
  for (int i = 0; i < N; i++)
  {
    cout << palLength[i] << " ";
  }
}
 
// Driver Code
int main()
{
  string S = "bababa";
  int N = S.length();
  printLongestPalindrome(S, N);
  return 0;
}
 
// This code is contributed by Kingash.


Java
// Java program for the above approach
 
class GFG {
 
    // Function to find for every index,
    // longest palindromic substrings
    // starting or ending at that index
    public static void
    printLongestPalindrome(String S,
                           int N)
    {
        // Stores the maximum palindromic
        // substring length for each index
        int palLength[] = new int[N];
 
        // Traverse the string
        for (int i = 0; i < N; i++) {
 
            // Stores the maximum length
            // of palindromic substring
            int maxlength = 1;
 
            // Consider that palindromic
            // substring ends at index i
            for (int j = 0; j < i; j++) {
 
                // If current character is
                // a valid starting index
                if (S.charAt(j) == S.charAt(i)) {
 
                    // If S[i, j] is palindrome,
                    if (isPalindrome(S, j, i)) {
 
                        // Update the length of
                        // the longest palindrome
                        maxlength = i - j + 1;
                        break;
                    }
                }
            }
 
            // Consider that palindromic
            // substring starts at index i
            for (int j = N - 1; j > i; j--) {
 
                // If current character is
                // a valid ending index
                if (S.charAt(j) == S.charAt(i)) {
 
                    // If str[i, j] is palindrome
                    if (isPalindrome(S, i, j)) {
 
                        // Update the length of
                        // the longest palindrome
                        maxlength = Math.max(j - i + 1,
                                             maxlength);
                        break;
                    }
                }
            }
 
            // Update length of the longest
            // palindromic substring for index i
            palLength[i] = maxlength;
        }
 
        // Print the length of the
        // longest palindromic substring
        for (int i = 0; i < N; i++) {
            System.out.print(palLength[i] + " ");
        }
    }
 
    // Function to return true if
    // S[i...j] is a palindrome
    public static boolean isPalindrome(
        String S, int i, int j)
    {
        // Iterate until i < j
        while (i < j) {
 
            // If unequal character encountered
            if (S.charAt(i) != S.charAt(j))
                return false;
            i++;
            j--;
        }
 
        // Otherwise
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "bababa";
        int N = S.length();
        printLongestPalindrome(S, N);
    }
}


Python3
# Python program for the above approach
 
# Function to return true if
# S[i...j] is a palindrome
def isPalindrome(S, i, j):
  # Iterate until i < j
  while (i < j):
    # If unequal character encountered
    if (S[i] != S[j]):
      return False
    i += 1
    j -= 1
 
  # Otherwise
  return True
 
# Function to find for every index,
# longest palindromic substrings
# starting or ending at that index
def printLongestPalindrome(S, N):
  # Stores the maximum palindromic
  # substring length for each index
  palLength = [0 for i in range(N)]
 
  # Traverse the string
  for i in range(N):
    # Stores the maximum length
    # of palindromic substring
    maxlength = 1
 
    # Consider that palindromic
    # substring ends at index i
    for j in range(i):
      # If current character is
      # a valid starting index
      if (S[j] == S[i]):
        # If S[i, j] is palindrome,
        if (isPalindrome(S, j, i)):
          # Update the length of
          # the longest palindrome
          maxlength = i - j + 1
          break
 
    # Consider that palindromic
    # substring starts at index i
    j = N-1
    while(j > i):
      # If current character is
      # a valid ending index
      if (S[j] == S[i]):
        # If str[i, j] is palindrome
        if (isPalindrome(S, i, j)):
          # Update the length of
          # the longest palindrome
          maxlength = max(j - i + 1, maxlength)
          break
      j -= 1
 
    # Update length of the longest
    # palindromic substring for index i
    palLength[i] = maxlength
 
  # Print the length of the
  # longest palindromic substring
  for i in range(N):
    print(palLength[i],end = " ")
 
# Driver Code
if __name__ == '__main__':
  S = "bababa"
  N = len(S)
  printLongestPalindrome(S, N)
   
  # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
class GFG
{
 
// Function to return true if
// S[i...j] is a palindrome
static bool isPalindrome(string S, int i, int j)
{
 
  // Iterate until i < j
  while (i < j)
  {
 
    // If unequal character encountered
    if (S[i] != S[j])
      return false;
    i++;
    j--;
  }
 
  // Otherwise
  return true;
}
 
// Function to find for every index,
// longest palindromic substrings
// starting or ending at that index
static void printLongestPalindrome(string S, int N)
{
 
  // Stores the maximum palindromic
  // substring length for each index
  int[] palLength = new int[N];
 
  // Traverse the string
  for (int i = 0; i < N; i++)
  {
 
    // Stores the maximum length
    // of palindromic substring
    int maxlength = 1;
 
    // Consider that palindromic
    // substring ends at index i
    for (int j = 0; j < i; j++)
    {
 
      // If current character is
      // a valid starting index
      if (S[j] == S[i])
      {
 
        // If S[i, j] is palindrome,
        if ((isPalindrome(S, j, i)) != false)
        {
 
          // Update the length of
          // the longest palindrome
          maxlength = i - j + 1;
          break;
        }
      }
    }
 
    // Consider that palindromic
    // substring starts at index i
    for (int j = N - 1; j > i; j--)
    {
 
      // If current character is
      // a valid ending index
      if (S[j] == S[i])
      {
 
        // If str[i, j] is palindrome
        if (isPalindrome(S, i, j))
        {
 
          // Update the length of
          // the longest palindrome
          maxlength = Math.Max(j - i + 1, maxlength);
          break;
        }
      }
    }
 
    // Update length of the longest
    // palindromic substring for index i
    palLength[i] = maxlength;
  }
 
  // Print the length of the
  // longest palindromic substring
  for (int i = 0; i < N; i++)
  {
    Console.Write(palLength[i] + " ");
  }
}
 
 
// Driver Code
static public void Main ()
{
    string S = "bababa";
  int N = S.Length;
  printLongestPalindrome(S, N);
}
}
 
// This code is contributed by code_hunt.


输出:
5 5 3 3 5 5

时间复杂度: O(N 3 )
辅助空间: O(1)