📜  最长回文子串 |设置 2

📅  最后修改于: 2022-05-13 01:57:07.736000             🧑  作者: Mango

最长回文子串 |设置 2

给定一个字符串,找出最长的回文子串。
例如:

Input: Given string :"forgeeksskeegfor", 
Output: "geeksskeeg".

Input: Given string :"Geeks", 
Output: "ee".

方法:动态编程解决方案已在上一篇文章中讨论过。基于动态规划的解决方案的时间复杂度为 O(n^2),它需要 O(n^2) 额外空间。我们可以在 (n^2) 时间内用 O(1) 额外空间找到最长的回文子串 (LPS)。

下面的算法非常简单易懂。这个想法是固定一个中心并在两个方向上扩展更长的回文,并跟踪迄今为止看到的最长的回文。

算法:

  1. 维护一个变量“ maxLength = 1 ”(用于存储 LPS 长度)和“start =0”(用于存储 LPS 的起始索引)。
  2. 这个想法很简单,我们将遍历整个字符串,i=0 到 i<(length of 字符串)。
    1. 遍历时,初始化'low '和'high '指针,使得low= i-1 高= i+1。
    2. 继续递增 'high' 直到str[high]==str[i] 。
    3. 同样,继续递减 'low' 直到str[low]==str[i]
    4. 最后,我们将继续增加 'high' 并减少 'low' 直到str[low]==str[high]
    5. 计算 length=high-low-1,如果 length > maxLength 然后 maxLength = length 和 start = low+1 。
  3. 打印 LPS 并返回 maxLength。

C++
// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
#include 
using namespace std;
 
// A utility function to print
// a substring str[low..high]
// This function prints the
// longest palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
int longestPalSubstr(string str)
{
    int n = str.size(); // calculating size of string
    if (n < 2)
        return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
    int maxLength = 1,start=0;
    int low, high;
    for (int i = 0; i < n; i++) {
        low = i - 1;
        high = i + 1;
        while ( high < n && str[high] == str[i]) //increment 'high'                                  
            high++;
       
        while ( low >= 0 && str[low] == str[i]) // decrement 'low'                   
            low--;
       
        while (low >= 0 && high < n && str[low] == str[high]){
              low--;
            high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length) {
            maxLength = length;
              start=low+1;
        }
    }
     
      cout<<"Longest palindrome substring is: ";
      cout<


C
// A O(n^2) time and O(1) space
// program to find the longest
// palindromic substring
#include 
#include 
 
// A utility function to print
// a substring str[low..high]
void printSubStr(char* str, int low, int high)
{
    for (int i = low; i <= high; ++i)
        printf("%c", str[i]);
}
 
// This function prints the longest
// palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
int longestPalSubstr(char* str)
{
    int n = strlen(str); // calculating size of string
    if (n < 2)
        return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
    int maxLength = 1,start=0;
    int low, high;
    for (int i = 0; i < n; i++) {
        low = i - 1;
        high = i + 1;
        while ( high < n && str[high] == str[i]) //increment 'high'                                  
            high++;
       
        while ( low >= 0 && str[low] == str[i]) // decrement 'low'                   
            low--;
       
        while (low >= 0 && high < n && str[low] == str[high]){
              low--; // decrement low
            high++; // increment high
        }
 
        int length = high - low - 1;
        if (maxLength < length) {
            maxLength = length;
              start=low+1;
        }
    }
    printf("Longest palindrome substring is: ");
      printSubStr(str,start,start+maxLength-1);
    return maxLength;
}
 
// Driver program to test above functions
int main()
{
    char str[] = "forgeeksskeegfor";
    printf("\nLength is: %d", longestPalSubstr(str));
    return 0;
}
// This is code is contributed by saurabh yadav


Java
// Java implementation of O(n^2)
// time and O(1) space method
// to find the longest palindromic substring
public class LongestPalinSubstring {
   
    // This function prints the
    // longest palindrome substring
    // (LPS) of str[]. It also
    // returns the length of the
    // longest palindrome
    static int longestPalSubstr(String str)
    {
        int n = str.length(); // calculcharAting size of string
        if (n < 2)
            return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
        int maxLength = 1,start=0;
        int low, high;
        for (int i = 0; i < n; i++) {
            low = i - 1;
            high = i + 1;
            while ( high < n && str.charAt(high) == str.charAt(i)) //increment 'high'                                  
                high++;
       
            while ( low >= 0 && str.charAt(low) == str.charAt(i)) // decrement 'low'                   
                low--;
       
            while (low >= 0 && high < n && str.charAt(low) == str.charAt(high) ){
                  low--;
                high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length){
            maxLength = length;
            start=low+1;
        }
    }   
    System.out.print("Longest palindrome substring is: ");
    System.out.println(str.substring(start, start + maxLength ));
    return maxLength;
       
 }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
 
        String str = "forgeeksskeegfor";
        System.out.println("Length is: "
                           + longestPalSubstr(str));
    }
}
// This is code is contributed by saurabh yadav


Python3
# A O(n ^ 2) time and O(1) space program to find the
# longest palindromic substring
 
# This function prints the longest palindrome substring (LPS)
# of str[]. It also returns the length of the longest palindrome
 
 
def longestPalSubstr(string):
    n = len(string) # calculating size of string
    if (n < 2):
        return n # if string is empty then size will be 0.
                  # if n==1 then, answer will be 1(single
                  # character will always palindrome)
    start=0
    maxLength = 1
    for i in range(n):
        low = i - 1
        high = i + 1
        while (high < n and string[high] == string[i] ):                              
            high=high+1
       
        while (low >= 0 and string[low] == string[i] ):                
            low=low-1
       
        while (low >= 0 and high < n and string[low] == string[high] ):
          low=low-1
          high=high+1
         
     
        length = high - low - 1
        if (maxLength < length):
            maxLength = length
            start=low+1
             
    print ("Longest palindrome substring is:",end=" ")
    print (string[start:start + maxLength])
     
    return maxLength
     
# Driver program to test above functions
string = ("forgeeksskeegfor")
print("Length is: " + str(longestPalSubstr(string)))
 
#This is code is contributed by saurabh yadav


C#
// C# implementation of O(n^2) time
// and O(1) space method to find the
// longest palindromic substring
using System;
 
class GFG {
 
    // This function prints the longest
    // palindrome substring (LPS) of str[].
    // It also returns the length of the
    // longest palindrome
    public static int longestPalSubstr(string str)
    {
        int n = str.Length; // calculcharAting size of string
        if (n < 2)
            return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
        int maxLength = 1,start=0;
        int low, high;
        for (int i = 0; i < n; i++) {
            low = i - 1;
            high = i + 1;
            while ( high < n && str[high] == str[i] ) //increment 'high'                                  
                high++;
       
            while ( low >= 0 && str[low] == str[i]) // decrement 'low'                   
                low--;
       
            while (low >= 0 && high < n && str[low] == str[high] ){
                  low--;
                high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length){
            maxLength = length;
            start=low+1;
        }
    }   
    Console.Write("Longest palindrome substring is: ");
    Console.WriteLine(str.Substring(start, maxLength));
    return maxLength;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "forgeeksskeegfor";
        Console.WriteLine("Length is: "
                          + longestPalSubstr(str));
    }
}
 
// This is code is contributed by saurabh yadav


Javascript


输出:

Longest palindrome substring is: geeksskeeg
Length is: 10

复杂性分析:

  • 时间复杂度: O(n^2),其中 n 是输入字符串的长度。
    遍历整个字符串的外循环,以及用于从 i 扩展的内循环。
  • 辅助空间: O(1)。
    不需要额外的空间。